Mongoose,nodejs,全文搜索

时间:2014-09-23 08:04:22

标签: javascript node.js mongodb mongoose full-text-search

我正在尝试使用Mongoose和nodejs设置简单的关键字全文搜索,这是到目前为止的代码:

var db = mongoose.createConnection('localhost', config.mongoDbName)
    , ContSchema = Schema({
        'idUser': String,
        'title': String,
        'category': String,
        'slug': String,
        'description': String
      })
      .index({
      'title':'text',
      'description':'text'
    })
 , ContModel = db.model('Cont', ContSchema);

db.on('error', function (err) {

        console.error.bind(console, 'Mongoose connection error:' + err);
    });
    db.once('open', function () {

      process.stdout.write('Connection to mongodb db done...');
    });

然后我会搜索查询:

var getAllBy = function (limit, offset, keywords) {

       var sort
        , find
        , findScore;

       if (!!keywords) {

        find = {'$text':{'$search':keywords}};
        findScore = {'score':{'$meta':'textMatchScore'}};
        sort = {'score':{'$meta':'textMatchScore'}};

       } else {

        sort = {'_id':'desc'};
       }

       return new RSVP.Promise(function (resolve, reject) {

        ContModel.find(find, findScore).limit(limit).skip(offset).sort(sort).exec(function (err, data) {

          if (err){

            reject(err);
          } else {

            resolve(data);
          }
        });
       });
}

它不起作用它在控制台中返回此错误: MongoError:无法规范化查询:BadValue错误排序规范

我实际上无法找到真正的问题,你可以帮我解决一下吗?

谢谢

1 个答案:

答案 0 :(得分:2)

此处的关键字不正确,请参阅$meta运算符下的正确语法,该运算符目前仅包含" textScore":

  find = {'$text':{'$search':keywords}};
  findScore = {'score':{'$meta':'textScore'}};
  sort = {'score': {'$meta':'textScore'} }