santhosh
santhosh

Reputation: 2008

MongoDB ensurIndex and createIndex using nodeJS?

I was not able to create index for profile:

var user = new Schema({
      profile : "String",
      fullname:"String"
   })
    user.statics.createIndexOfProfile = function(callback){
    this.ensureIndex("profile",function(err,doc){
        if(err) {
          console.log(err+'sna');
          callback(err);
        }
         else {
          console.log(doc+'santhosh');
          callback(null,doc);
        }
      });

I was getting error like this.ensureIndex is not a function

Upvotes: 4

Views: 13324

Answers (2)

zangw
zangw

Reputation: 48566

The correct API is ensureIndexes, which Sends ensureIndex commands to mongo for each index declared in the schema.

Here is one sample

var UserSchema = new Schema({
    profile : {type: String, index: true},
    fullname: String
});

var User = mongoose.model('User', UserSchema);

User.ensureIndexes(function(err) {
    if (err)
        console.log(err);
    else
        console.log('create profile index successfully');
});

Or through index

var UserSchema = new Schema({
    profile : {type: String, index: true},
    fullname: String
});

UserSchema.index({ profile: 1 });

var User = mongoose.model('User', UserSchema);

After running the above codes, then check the indexes from MongoDB.

> db.users.getIndexes()
[
        {
                "v" : 1,
                "key" : {
                        "_id" : 1
                },
                "name" : "_id_",
                "ns" : "test.users"
        },
        {
                "v" : 1,
                "key" : {
                        "profile" : 1
                },
                "name" : "profile_1",
                "ns" : "test.users",
                "background" : true
        }
]

Upvotes: 7

oleh.meleshko
oleh.meleshko

Reputation: 4795

If you want to add an index to some field, just add index: true to its definition.

So you can do the following:

var user = new Schema({
    profile : { type: String, index: true }, // field level
    // ...
});

or

user.index({ profile: 1 }); // schema level

From mongoose docs:

When your application starts up, Mongoose automatically calls ensureIndex for each defined index in your schema. Mongoose will call ensureIndex for each index sequentially, and emit an 'index' event on the model when all the ensureIndex calls succeeded or when there was an error.

Upvotes: 1

Related Questions