Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 541
asliwinski Avatar asked Feb 25 '18 16:02

asliwinski


2 Answers

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"}})
like image 141
asliwinski Avatar answered Oct 16 '22 15:10

asliwinski


In the current version of the native MongoDB driver, you need to include the projection key among the options for find:

const results = await collection.find(
  {
    $text: { $search: filter }
  },
  {
    projection: { score: { $meta: 'textScore' } },
    sort: { score: { $meta: 'textScore' } },
  }
).toArray();
like image 26
Dan Dascalescu Avatar answered Oct 16 '22 15:10

Dan Dascalescu