Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 788
santhosh Avatar asked Feb 07 '23 18:02

santhosh


2 Answers

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
        }
]
like image 62
zangw Avatar answered Feb 12 '23 08:02

zangw


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.

like image 21
oleh.meleshko Avatar answered Feb 12 '23 09:02

oleh.meleshko