Mongoose Unique index not working!

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/


Oops! You just have to restart mongo.


I've done something like this:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const FooSchema = new Schema({
   name: { type: String, required: true, index: true, unique: true }
});

const Foo = mongoose.model('Foo', FooSchema);

Foo.createIndexes();

module.exports = Foo

I added the Foo.createIndexes() line b.c. I was getting the following deprecation warning when the code was being ran:

(node:21553) DeprecationWarning: collection.ensureIndex is deprecated. Use createIndexes instead.

I'm not sure if Foo.createIndexes() is asynchronous, but AFAIK things seem to be working fine


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()