【问题标题】:How to access Text Score MongoDB $text search如何访问文本分数 MongoDB $文本搜索
【发布时间】:2016-12-31 21:34:34
【问题描述】:

我成功地在 Node.js 代码中使用 Mongoose 运行 $text 搜索。这是我使用的代码:

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 创建的分数?

【问题讨论】:

  • 您可以展示您的商品吗?当你做console.log(item) 时的样子
  • { _id: 57bd960dd6499fef9dad4f01, cName: 'XYZ', cAddress: ' ', __v: 0, score: 1.0073315117131936, contentSection: [], .....}
  • “score”是结果中返回的字段。我可以访问文档的所有其他字段并处理/打印它们 - 除了分数。

标签: node.js mongodb mongoose mongodb-query text-search


【解决方案1】:

好吧我想通了……需要做的事情如下:

console.log(item._doc.score);

这样就行了!

【讨论】:

  • 谢谢!找不到太多关于此的信息。
  • 感谢您的跟进,这让我发疯了!
【解决方案2】:

Model.find() 返回一个 mongoose Document 而不是一个普通的 Javascript 对象。我猜当您尝试访问属性“score”时,会发生某种验证,并且因为您的架构中没有它,它会返回undefined

在我看来,获取item.score 值的最佳方法是将mongoose Document 对象转换为纯Javascript 对象。

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

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

或者(如果您需要 mongoose 文档用于其他目的)您可以使用 Document.prototype.toObject() 方法获取纯 javascript 对象:

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);
  });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-28
    • 2012-03-26
    • 1970-01-01
    • 2017-12-03
    • 2022-12-05
    • 2019-05-08
    • 2018-09-27
    • 1970-01-01
    相关资源
    最近更新 更多