无法访问对象的一个​​属性,它是未定义的

时间:2017-07-18 19:11:18

标签: javascript node.js

我正在使用全文搜索MongoDB。当我登录日志时,我可以用我的分数看到我的结果。但是我无法在我的代码中访问此属性

function bestMatch(name){

  ChebiEntry.find({$text: {$search: name}},
  {score: {$meta: 'textScore'}},(e,results)=>{
    if (results.length > 0){
      results.forEach((obj)=>{
        console.log(JSON.stringify(obj)); // This works, I see .score
        console.log(obj.score); // .score is allegedly undefined here...
      })

    } else {
      {
        return false;
      }
    }
  })
  .sort({score: {$meta: 'textScore'}})
}

这是我的输出。如您所见,我的字符串化对象包含我需要的一切。但是当我尝试阅读.score时,它是未定义的。所有其他属性都可以正常工作。

{"_id":"596d55fd2c446456a0ceb4be","id":3473,"name":"Cation","__v":0,"score":1.1}
undefined
{"_id":"596d560b2c446456a0cf10fc","id":23058,"name":"cation","__v":0,"score":1.1}
undefined
{"_id":"596d561e2c446456a0cfb067","id":36916,"name":"cation","__v":0,"score":1.1}
undefined
{"_id":"596d56032c446456a0ced48d","id":23058,"name":"cations","__v":0,"score":1}
undefined
{"_id":"596d561e2c446456a0cfb066","id":36916,"name":"cationes","__v":0,"score":1}
undefined
{"_id":"596d55fb2c446456a0cea1d6","id":4665,"name":"Divalent cation","__v":0,"score":0.75}
undefined
{"_id":"596d55ff2c446456a0ceccb1","id":9175,"name":"sodium(I) cation","__v":0,"score":0.75}
undefined

1 个答案:

答案 0 :(得分:1)

JSON.stringify()工作原因并尝试直接访问密钥的原因不是因为JSON.stringify()使用Object#toJSON()预处理对象,如果对象上存在方法。为了解决您的问题,您可以执行以下操作:

results
  .map(obj => obj.toJSON())
  .forEach(obj => {
    console.log(obj.score);
  })

I've answered a similar question here,除了在这种情况下,用户尝试使用for...in迭代未处理对象的可枚举属性,并在枚举其键之前调用对象上的.toJSON()问题。

或者,according to this,您可以将选项{lean: true}传递给您的查询,如下所示:

ChebiEntry.find(
  {$text: {$search: name}},
  {score: {$meta: 'textScore'}},
  {lean: true},
  (e, results) => {
    ...
  })
  ...

并保持其余代码不变,这意味着您无需在对象上明确调用toJSON()