MongoError: must have $meta projection for all $meta sort keys using Mongo DB Native NodeJS Driver

MongoError: must have $meta projection for all $meta sort keys using Mongo DB Native NodeJS Driver

运行 直接在 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

我做错了什么?

OK,根据this bug since the version 3.0.0 find and findOne no longer supportfields参数和query需要改写如下:

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

在当前版本的原生MongoDB驱动中,需要包含projection key among the options for find:

const results = await collection.find(
  {
    $text: { $search: filter }
  },
  {
    projection: { score: { $meta: 'textScore' } },
    sort: { score: { $meta: 'textScore' } },
  }
).toArray();