【问题标题】:Not able to return Object property values in NodeJS无法在 NodeJS 中返回 Object 属性值
【发布时间】:2021-10-28 04:33:31
【问题描述】:

我想返回对象属性值,但点属性访问器不起作用。以下是我的功能:

async abc(reviewId){
    
    let b = this.get(reviewId) 
    return b
  }

下面是 get 函数 abc() 调用:

async get(reviewId) {
    const restaurantsCollection = await restaurants();
    reviewId = ObjectId(reviewId)
  
    const r = await restaurantsCollection.findOne(
      { reviews: { $elemMatch: { _id : reviewId } } },
      {"projection" : { "reviews.$": true }}
    )
  
    return r.reviews[0]

    
  }

我可以返回 b:

{
  _id: new ObjectId("617a07afeae615cff755fec7"),
  title: 'tkl',
  reviewer: 'sm',
  rating: 1,
  dateOfReview: '15/1/2002',
  review: ' ruh'
}

当我返回 b.rating 时,它返回 undefined:

async abc(reviewId){

    let b = this.get(reviewId) 
    return b.rating
  }

我错过了什么?

【问题讨论】:

  • 从 mongodb 获得的一组数据的引用会有所帮助,但您在返回 b.rating 之前尝试过 JSON.stringify(JSON.parse(b)) 吗?
  • 当我添加这个时我得到这个错误:SyntaxError: Unexpected token o in JSON at position 1,我想我必须使用 findOne 来获取整个对象然后得到评级,谢谢你的评论

标签: node.js mongodb object


【解决方案1】:

我不得不在我的代码中使用 await,因为 promise 正在等待,所以 b.ratings 是未定义的。

async abc(reviewId){

    let b = await this.get(reviewId) 
    return b.rating
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-13
    • 2021-08-22
    • 2018-02-07
    • 1970-01-01
    • 1970-01-01
    • 2018-06-22
    • 1970-01-01
    • 2018-01-22
    相关资源
    最近更新 更多