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?
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"}})
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With