3

I need to create an index in MongoDB to store unique slugs.

I use this code to generate the index:

this._db = db;
this._collection = this._db.collection("Topics");
this._collection.ensureIndex( { slug: 1 }, { unique: true });

But when I run my tests it fails on the "beforeEach": (I'm using mongo-clean NPM)

beforeEach(function (done) {
    clean(dbURI, function (err, created) {
        db = created;
        instance = topicManager(db);
        done(err);
    });
});

Saying:

Uncaught Error: Cannot use a writeConcern without a provided callback

What am I doing wrong? (if I comment the ensureIndex everything works)

Fez Vrasta
  • 14,110
  • 21
  • 98
  • 160

2 Answers2

5

As the response implies, you might need to provide a callback function to your call to ensureIndex:

this._db = db;
this._collection = this._db.collection("Topics");
this._collection.ensureIndex( { slug: 1 }, { unique: true }, function(error) {
  if (error) {
   // oops!
  }});
E_net4
  • 27,810
  • 13
  • 101
  • 139
  • Can't I handle it during the insert? – Fez Vrasta Jun 29 '14 at 14:18
  • The callback function is not used for handling future operations to the database, but to ensure that the index was successfully created. When inserting new documents, you are also expected to provide callback functions. – E_net4 Jun 29 '14 at 14:19
  • Ok but if I want to try to insert something and in case I get an error because the slug is not unique I want to change the slug and try again how can I do? I thought it was possible with unique indexes – Fez Vrasta Jun 29 '14 at 14:21
  • Indeed, you can do that with a callback function: if an insert operation fails with error code 11000, it means a duplicate key collision occurred. See an example log: http://pastebin.com/KPmYxZvw – E_net4 Jun 29 '14 at 14:25
  • Ok... If I add a callback my insert returns, beside the element I've inserted, a `[Error: Connection was destroyed by application]`. Without ensureIndex I don't get this... – Fez Vrasta Jun 29 '14 at 14:31
  • That sounds like a distinct issue from what you are trying to solve with this question. Try updating it with the problems that you currently have. – E_net4 Jun 29 '14 at 14:37
  • I've opened a different question: http://stackoverflow.com/questions/24477420/ensureindex-causes-error – Fez Vrasta Jun 29 '14 at 15:16
2

ensueIndex() is now deprecated in v^3.0.0

For those who use ^3.0.0:

Deprecated since version 3.0.0: db.collection.ensureIndex() is now an alias for db.collection.createIndex().

https://docs.mongodb.com/manual/core/index-unique/#index-type-unique

Example:

db.members.createIndex( { "user_id": 1 }, { unique: true } )
kenju
  • 5,866
  • 1
  • 41
  • 41