Reputation: 133
recipe.find({
$text: {
$search: req.query.search,
$diacriticSensitive: true
}
}, {
score: {
$meta: "textScore"
}
}
,function(err, data) { });
I am using mongoose text search functionality to sort the result based on their score. I also need to list the non matching records to the bottom of the list. Can i achieve this ? Is there any way to display recods with zero score?
Upvotes: 0
Views: 631
Reputation: 1498
You can return all documents from 'recipe', even non-matching ones, by doing 'OR' on a text search and a statement that always returns true. The non-matching results will receive a score of 0. A side effect of this seems to be that Mongo does not want to sort by the text score (if you try to sort on a mongo console), but this should not be a problem in your case since you can easily sort in the client (e.g., using lodash etc). Sample code (not tested):
recipe.find({
$or: [{
$text: {
$search: req.query.search,
$diacriticSensitive: true
}
}, {
_id: {
$exists: true
}
}]
}, {
score: {
$meta: "textScore"
}
},
function(err, data) {
if (data) {
data = _.map(data, function(d) {
return d.toObject();
});
data = _.orderBy(data, ['score'], ['desc']);
}
}
);
Upvotes: 1