Search code examples
node.jsmongodbmongodb-queryfull-text-searchnode-mongodb-native

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


Running the following text search directly on MongoDB results in no issues:

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

However when trying to run the same query using the 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);
      });
    });
  });
}

I'm getting the following error:

MongoError: must have $meta projection for all $meta sort keys

What am I doing wrong here?


Solution

  • OK, according to this bug since the version 3.0.0 find and findOne no longer support the fields parameter and the query needs to be rewritten as follows:

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