Mongoose Unique index not working!
I'm trying to let MongoDB detect a duplicate value based on its index. I think this is possible in MongoDB, but through the Mongoose wrapper things appear to be broken. So for something like this:
User = new Schema ({
email: {type: String, index: {unique: true, dropDups: true}}
})
I can save 2 users with the same email. Darn.
The same issue has been expressed here: https://github.com/LearnBoost/mongoose/issues/56, but that thread is old and lead to nowhere.
For now, I'm manually making a call to the db to find the user. That call is not expensive since "email" is indexed. But it would still be nice to let it be handled natively.
Does anyone have a solution to this?
Solution 1:
Oops! You just have to restart mongo.
Solution 2:
Oops! You just have to restart mongo.
And re-index too, with:
mongo <db-name>
> db.<collection-name>.reIndex()
In testing, since I don't have important data, you can also do:
mongo <db-name>
> db.dropDatabase()
Solution 3:
I ran into the same issue: I added the unique constraint for the email
field to our UserSchema
after already having added users to the db, and was still able to save users with dupe emails. I resolved this by doing the following:
1) Remove all documents from the users collection.
2) From the mongo shell, execute the command:
db.users.createIndex({email: 1}, {unique: true})
Regarding step 1, note that from Mongo's docs:
MongoDB cannot create a unique index on the specified index field(s) if the collection already contains data that would violate the unique constraint for the index.
https://docs.mongodb.com/manual/core/index-unique/