Mongoose unique index not working

拟墨画扇 提交于 2019-12-10 11:42:29

问题


I don's want duplicate usernames to be able to sign-up on my website. So, I place something like this in mongoose model:

var userSchema = new mongoose.Schema({
  username: { type: String, index: { unique: true }}, 
  password: String
});

But when I create a new user in the controller like below, it does not throw an exception and creates a duplicate.

mongoose.model('User').create({
    username : email,
    password : password
}, function(err, user) {
    if (err) {
        // WHY DOES IT NOT THROW ERROR AND GET HERE?
    }
});

I have already tried to restart my application and mongod process.


回答1:


I finally found a fix to this issue I was also having

you need to

npm install mongoose-unique-validator



来源:https://stackoverflow.com/questions/35613425/mongoose-unique-index-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!