wazzaday
wazzaday

Reputation: 9664

ensuring unique index mongodb

I am trying to ensure an index is unique in mongodb, im using node.js however it simply does not work.

//ensures unique data only
db.social_media.ensureIndex( { name: 1 }, { unique: true } );

db.social_media.insert({name:'stan'}, function(err, docs){
    console.log(err);
    console.log(docs);
});

db.social_media.insert({name:'stan'}, function(err, docs){
    console.log(err);
    console.log(docs);
});

The following output is:

null
{ name: 'stan', _id: 53e9d2ee88b96dd224c6333f }
null
{ name: 'stan', _id: 53e9d2ee88b96dd224c63340 }

Meaning both docs where inserted - even though I specifically specified that 'name' should be unique. Am I missing something here?

Upvotes: 1

Views: 1206

Answers (1)

Leonid Beschastny
Leonid Beschastny

Reputation: 51440

You're starting inserting documents before your index is ensured, thus creating a race condition.

Unique index can not be created if your collection contains duplicate keys.

Try the following code (but first ensure that your collection is empty, or at least contains no duplicate keys):

//ensures unique data only
db.social_media.ensureIndex({
  name: 1
}, {
  unique: true
}, function (err) {
  if (err) {
    console.log('ensureIndex failed', err);
  } else {
    db.social_media.insert({name:'stan'}, console.log);
    db.social_media.insert({name:'stan'}, console.log);
  }
});

Upvotes: 1

Related Questions