0

I'm trying to enforce uniqueness by field on a mongoose model, in an existing database.

const UserSchema = new mongoose.Schema({
  email: {
    type: String,
    required: true,
    unique: true,
  }
})

Then when I create a user with an email that is already assigned, it passes, and I have 2 users with the same email.

I have read all related SO answers > 2015 and all about dropDups, which is deprecated.

I think I fixed this issue by manually running

db.users.createIndex({email:1}, {unique:true})

However this obviously becomes cumbersome both in development and in production, especially considering the mongoose docs state that the attribute takes care of it:

unique: boolean, whether to define a unique index on this property.

Can someone provide a clear solution to enforcing uniqueness by field on a Mongoose model, considering an existing database and a fresh collection? Thanks

softcode
  • 4,358
  • 12
  • 41
  • 68
  • Possible dupe of https://stackoverflow.com/questions/30966146/mongoose-schema-unique-not-being-respected – JohnnyHK Feb 06 '17 at 21:52
  • @JohnnyHK How is this a possible dupe? Are you suggesting that everytime you want to add a collection with unique fields you must manually call `db.collection.dropIndex('fieldName_1')` ? Doesn't answer my question at all – softcode Feb 06 '17 at 21:59
  • What often happens is that you don't realize that the collection already has a (non-unique) index on the field, so Mongoose doesn't add the unique index you've defined. What does `db.users.getIndexes()` show? – JohnnyHK Feb 06 '17 at 22:03
  • I dropped the collection to start fresh and created a new user. `db.users.getIndexes()` now shows `[ { "v" : 2, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "testdb.users" } ]` @JohnnyHK – softcode Feb 06 '17 at 22:08
  • You may have `autoIndex` disabled in your environment. Try enabling it by adding a call to `UserSchema.set('autoIndex', true);` and trying it again. – JohnnyHK Feb 06 '17 at 22:14
  • @JohnnyHK Ok done, and what should I expect there to happen ? – softcode Feb 06 '17 at 22:29
  • It should automatically create the index for you. Docs [here](http://mongoosejs.com/docs/guide.html#indexes). – JohnnyHK Feb 06 '17 at 22:31
  • @JohnnyHK ok... But if autoIndex is set to false and unique is set to true on a field, shouldn't mongoose build the index for that field anyways? I'm not sure I'm following where we're trying to get with this – softcode Feb 06 '17 at 22:36

1 Answers1

1

Two user has been created before unique index has been created.So you can insert two users with same email.You can try code below, it make sure all index has been created:

UserModel.on('index', function(error) {
  const user1 = new UserModel({
    email: '3489'
  });

  const user2 = new UserModel({
    email: '3489'
  });
  user1.save(console.log);
  user2 .save(console.log);
});
王如锵
  • 941
  • 7
  • 17