Question

I'm trying to purposely create and attempt to write a duplicate on a unique index on MongoDB for testing purposes. My code is essentially:

db.collection("foo").ensureIndex({a: 1}, {unique: true}, function () {
    db.collection("foo").insert({a: "foo"}, function () {
        db.collection("foo").insert({a: "foo"});
    });
});

However, this doesn't fail in any way. If I connect to my DB and run db.foo.find({a: "foo"}) I will find two results after this is run. This indicates that the {unique: true} is not working properly/not doing anything/etc.

Using createIndex does not work either.

Am I using MongoDB unique indices incorrectly?

Was it helpful?

Solution

You're creating the index correctly, but not correctly responding to potential errors being sent from the DB.

As you're using NodeJS, you need to check the first parameter of callbacks to check for errors (most NodeJS APIs with callbacks follow this pattern, as does the MongoDB NodeJS Native driver):

db.collection("foo").ensureIndex({a: 1}, {unique: true}, function (err) {
    if(err) { console.log('failed to create index: ', err); return; }
    db.collection("foo").insert({a: "foo"}, function (err) {
          if(err) { console.log('first insert failed: ', err); return; }
          db.collection("foo").insert({a: "foo"}, function (err) {
              if(err) { 
                   console.log('insert failed:', err); 
                   return;  
              }
        });
    });
});

OTHER TIPS

after i tryed in my mongo, i'm afraid the code is useful. and the record will be unique after ensure-index. you may check you mongo version or set err in callback to find any syntax err.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top