简体   繁体   中英

Unique index not working on Mongoose schema

I have a schema setup like this:

var UserSchema = new Schema({
  id: {type: String, required: true, unique: true, index: true, default: mongoose.Types.ObjectId},

  name: { type: String, required: true },
  email: { type: String, required: true, unique: true, index: true },
  mobile: { type: String, unique: true, sparse: true },
  password: { type: String, required: true }

});

Seems to work great except the email field is letting in duplicates, despite have unique:true set. I do the following:

User.create({
  name: req.body.name,
  email: req.body.email,
  mobile: req.body.mobile,
  password: password
}, function(err, user) {
  if (err) return res.send({ invalid : true });
});

If req.body.email is a value that's already in the database, the query above should return err . But it doesn't, it creates the new user perfectly fine, resulting in duplicate emails in the database.

Why is this happening?

mongo and hence mongoose will assign an automatic id fields to your document. usually that is "_id". Try removing the "id" from your schema to fix your issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM