使用nodeJS的MongoDB ensurIndex和createIndex?

san*_*osh 3 indexing mongoose mongodb node.js

我无法为以下内容创建索引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);
        }
      });
Run Code Online (Sandbox Code Playgroud)

我得到的错误就像 this.ensureIndex is not a function

zan*_*ngw 7

正确的API是ensureIndexes,ensureIndex为模式中index 声明的每个命令发送mongo命令.

这是一个样本

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');
});
Run Code Online (Sandbox Code Playgroud)

或者通过 index

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

UserSchema.index({ profile: 1 });

var User = mongoose.model('User', UserSchema);
Run Code Online (Sandbox Code Playgroud)

运行上面的代码后,检查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
        }
]
Run Code Online (Sandbox Code Playgroud)