【问题标题】:MongoDB ensurIndex and createIndex using nodeJS?使用nodeJS的MongoDB ensurIndex和createIndex?
【发布时间】:2016-05-27 09:00:04
【问题描述】:

我无法为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);
        }
      });

我收到了类似this.ensureIndex is not a function的错误

【问题讨论】:

    标签: node.js mongodb indexing mongoose


    【解决方案1】:

    正确的 API 是ensureIndexes,它为架构中声明的每个index 发送ensureIndex 命令到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');
    });
    

    或通过index

    var UserSchema = new Schema({
        profile : {type: String, index: true},
        fullname: String
    });
    
    UserSchema.index({ profile: 1 });
    
    var User = mongoose.model('User', UserSchema);
    

    运行上述代码后,从 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
            }
    ]
    

    【讨论】:

    • 但是如何搜索。当我做 user.find({$text:{$search:"MBBS"}},function(err,doc){ if(err) cosnole.log(err) else console.log(doc) })
    • errror is like "$err": "Unable to execute query: error processing query: ns=user.profile limit=1000 skip=0\nTree: TEXT : query=santhosh, language=, tag =NULL\nSort: {}\nProj: {}\n 规划器返回错误:$text 查询需要一个文本索引",
    • @santhosh,试试UserSchema.index({ profile: 'text' });
    • @zangw ,如果你能看看,感激不尽..stackoverflow.com/questions/35426213/…
    • 通过从 mongo shell 获取索引,我能够看到索引的创建
    【解决方案2】:

    如果您想为某个字段添加索引,只需在其定义中添加index: true

    因此您可以执行以下操作:

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

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

    来自mongoosedocs

    当您的应用程序启动时,Mongoose 会自动调用 确保架构中每个已定义索引的索引。猫鼬会打电话 为每个索引顺序确保索引,并发出一个“索引”事件 所有 ensureIndex 调用成功或存在时的模型 一个错误。

    【讨论】:

      猜你喜欢
      • 2020-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-12
      • 2017-08-01
      • 2018-07-26
      • 2018-10-10
      相关资源
      最近更新 更多