直接在MongoDB上运行以下文本搜索不会导致任何问题:

db.getCollection('schools').find({
  $text:
    {
      $search: 'some query string',
      $caseSensitive: false,
      $diacriticSensitive: true
    }
}, {score: {$meta: "textScore"}}).sort({score:{$meta:"textScore"}})

但是,当尝试使用native NodeJS driver运行相同的查询时:
function getSchools(filter) {
  return new Promise(function (resolve, reject) {

    MongoClient.connect('mongodb://localhost:60001', function(err, client) {
      const collection = client.db('schools').collection('schools');

      collection.find({
        $text:
          {
            $search: filter,
            $caseSensitive: false,
            $diacriticSensitive: true
          }
        }, {score: {$meta: "textScore"}}).sort({score:{$meta:"textScore"}}).toArray(function(err, docs) {
        if (err) return reject(err);

        resolve(docs);
      });
    });
  });
}

我收到以下错误:
MongoError: must have $meta projection for all $meta sort keys

我在这里做错了什么?

最佳答案

好的,根据this bug,因为版本3.0.0是findfindOne no longer support,所以fields参数和查询需要按以下方式重写:

collection.find({
        $text:
          {
            $search: filter,
            $caseSensitive: false,
            $diacriticSensitive: true
          }
        })
        .project({ score: { $meta: "textScore" } })
        .sort({score:{$meta:"textScore"}})

关于node.js - MongoError : must have $meta projection for all $meta sort keys using Mongo DB Native NodeJS Driver,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48975707/

10-16 11:17