3

I was successful in running $text search using Mongoose in Node.js code. Here is the code I used:

Model.find( 
     { $text : { $search : "FindThisString"}},
     { score : {$meta : "textScore"}}
  )
 .sort({ score : { $meta : 'textScore'}})
 .exec(function(err, results) {
     _.each(results, function(item) {
        //console.log(item);
        console.log(item._id);
        console.log(item.score);
     });
});

When I console log the entire document, I can see the "score" field in on the console, but "item.score" prints as "undefined".

How can I access the score created by MongoDB in the returned results?

Ashu Joshi
  • 540
  • 3
  • 11

2 Answers2

5

Alright I figured it out... what needs to be done as follows:

console.log(item._doc.score);

That will do the trick!

Ashu Joshi
  • 540
  • 3
  • 11
1

Model.find() returns a mongoose Document instead a plain Javascript object. I guess that when you try to access to the property "score", some kind of validation occurs and because you don't have it in you schema, it returns undefined.

In my opinion, the best way to get the value of item.score, is by converting the mongoose Document object into a plain Javascript object.

For that purpose you can make Model.find() to return a plain object by using the { lean: true } option (see here and here for more information):

Model.find( 
  { $text : { $search : "FindThisString"}},
  { score : {$meta : "textScore"}},
  { lean: true }
)
.sort({ score : { $meta : 'textScore'}})
.then( (result) => {
  result.forEach(item => console.log(item.score));
});

Or (in case you need the mongoose Document for other purposes) you can get the plain javascript object by using Document.prototype.toObject() method:

Model.find( 
  { $text : { $search : "FindThisString"}},
  { score : {$meta : "textScore"}}
)
.sort({ score : { $meta : 'textScore'}})
.then( (result) => {
  result.forEach(itemDocument => {
    const item = itemDocument.toObject();
    console.log(item.score);
  });
});
Silveste
  • 189
  • 2
  • 11