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;
}
});
});
});