1

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.

Darth.Vader
  • 5,079
  • 7
  • 50
  • 90
  • 1
    Possible dupe of http://stackoverflow.com/questions/30966146/mongoose-schema-unique-not-being-respected – JohnnyHK Feb 24 '16 at 21:34
  • 2
    What `db.user.getIndexes` returns? What version of mongoose you use? – Alex Blex Feb 24 '16 at 21:35
  • 1
    If you are not getting duplicate key errors then most definately the index does not exist. A really good reason for this is that the existing data already contains "duplicate keys" and therefore the index creation errors. See [Remove Duplicates From MongoDB](http://stackoverflow.com/questions/31557053/remove-dups-from-mongodb/31558107#31558107) for discussion of how to identify and remove. If `.aggregate()` turns out too large (unlikely), then you can always write to another collection with "upserts" instead. – Blakes Seven Feb 25 '16 at 00:21

1 Answers1

3

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

you need to

npm install mongoose-unique-validator

ByronC
  • 31
  • 2