Fez Vrasta
Fez Vrasta

Reputation: 14835

ensureIndex asks for callback

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)

Upvotes: 3

Views: 943

Answers (2)

kenju
kenju

Reputation: 5954

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

Upvotes: 2

E_net4
E_net4

Reputation: 30092

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

Upvotes: 5

Related Questions