Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 如何访问文本分数MongoDB$文本搜索_Node.js_Mongodb_Mongoose_Mongodb Query_Text Search - Fatal编程技术网

Node.js 如何访问文本分数MongoDB$文本搜索

Node.js 如何访问文本分数MongoDB$文本搜索,node.js,mongodb,mongoose,mongodb-query,text-search,Node.js,Mongodb,Mongoose,Mongodb Query,Text Search,我在Node.js代码中使用Mongoose成功地运行了$text search。以下是我使用的代码: Model.find( { $text : { $search : "FindThisString"}}, { score : {$meta : "textScore"}} ) .sort({ score : { $meta : 'textScore'}}) .exec(function(err, results) { _.each(results, f

我在Node.js代码中使用Mongoose成功地运行了$text search。以下是我使用的代码:

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);
     });
});
当我在控制台上记录整个文档时,我可以在控制台上看到“score”字段,但“item.score”打印为“undefined”


我如何在返回的结果中访问MongoDB创建的分数?

好吧,我知道了。。。需要做的工作如下:

控制台日志(项目\单据分数)

那就行了

Model.find()返回一个Javascript对象,而不是一个普通Javascript对象。我猜当您尝试访问属性“score”时,会发生某种验证,因为您的模式中没有它,所以它返回
未定义的

在我看来,获取
item.score
值的最佳方法是将mongoose文档对象转换为普通Javascript对象

为此,您可以使用
{lean:true}
选项使Model.find()返回普通对象(有关更多信息,请参阅和):

或者(如果出于其他目的需要mongoose文档),可以使用以下方法获取普通javascript对象:


你能展示一下你的物品吗?执行
console.log(item)
{id:57bd960dd6499fef9dad4f01,cName:'XYZ',cadAddress:'',u v:0,score:1.0073315117131936,contentSection:[],…}“score”是结果中返回的字段。我可以访问文档的所有其他字段并处理/打印它们-除了分数。谢谢!找不到关于此的更多信息。感谢您的跟进,这让我发疯了!
Model.find( 
  { $text : { $search : "FindThisString"}},
  { score : {$meta : "textScore"}},
  { lean: true }
)
.sort({ score : { $meta : 'textScore'}})
.then( (result) => {
  result.forEach(item => console.log(item.score));
});
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);
  });
});