Reputation: 6469
I have an array field called udids
in Meteor.users
schema, which should contains unique elements. This is how I defined the index using SimpleSchema and Collection2:
new SimpleSchema({
...
udids: {
type: Array,
index: true,
unique: true,
optional: true,
sparse: true,
},
'udids.$': {
type: String,
},
...
})
However, when I start the app, I got this error: E11000 duplicate key error collection: meteor.users index: c2_udids dup key: { : undefined }
.
I tried searching for the documents with udids = undefined
in the database: db.users.find({ udids: { $type: 6 } })
($type: 6
for undefined
value) but it returns nothing.
Upvotes: 2
Views: 1624
Reputation: 6469
The error message is a bit unclear so I had to guess the reason why. I found out that the current database already has some users with udids = []
. I'm writing a migration script to unset this field from those users. Hopefully this will help others who have the same problem as me.
Upvotes: 2
Reputation: 2870
I've not tested this, but it should ideally work.
Meteor.users
as a collection name. You may want to replace it with whichever collection you want to run the validation against. new SimpleSchema({
...
'udids': {
optional: true,
type: [String], // an array of string eg. ['A','B']
custom: function() {
// this.value = current field's value
// Below mongo query will check to see if there is at least one
// mongo doc whose udids contains the currently entered field's value.
// if found, then return the error message.
if (Meteor.users.findOne({
udids: {
$in: [this.value]
}
})) {
return "duplicateMsg";
}
},
...
});
SimpleSchema.messages({ duplicateMsg:"Udid already exists"});
Upvotes: 0