Darth.Vader
Darth.Vader

Reputation: 6291

Mongoose unique index not working

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.

Upvotes: 1

Views: 1791

Answers (1)

ByronC
ByronC

Reputation: 31

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

you need to

npm install mongoose-unique-validator

Upvotes: 3

Related Questions