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

2

9

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?

Osmium answered 25/2, 2018 at 16:23 Comment(0)
O
21

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"}})
Osmium answered 25/2, 2018 at 16:36 Comment(4)
find documentation here: mongodb.github.io/node-mongodb-native/3.0/api/…Ingra
So why don't they update the textScore sort example in their very own documentation accordingly?! :rolleyes: Thanks for pointing this out! Probably saved me quite some time, especially because the error message doesn't give a very good hint to the actual error...Destructive
Hi can anyone tell me if I had to sort in reverse order of the same query?Sheriesherif
@Destructive because those are the docs for the mongo shell, the nodejs driver docs are hereTorras
J
4

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();
Joaquin answered 19/4, 2019 at 7:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.