从等待访问对象-NodeJS

时间:2019-03-24 15:46:23

标签: node.js async-await

我的路线之一是返回来自mongodb的对象。收到对象时,我需要访问其键,但是我尝试访问的每个键都以未定义的形式返回。

代码:

const express = require('express')
const Review = require('../models/review')
const router = new express.Router()


router.get('/',async (req,res)=>{
    try{
        const results = await Review.findById('some_id')
        const finalResult = JSON.parse(results) //still failing
        res.send(finalResult.rating)
    }catch (e){
        res.status(400).send(e)
    }
})

module.exports = router

响应:

{
"_id": "",
"reviewerName": "Jane Doe",
"reviewDate": "2019-02-19T19:30:54.000Z",
"siteSource": "ReviewSite",
"rating": 5,
"reviewText": "Some text",
}

我试图通过做`console.log(results.rating)访问该评分,但是返回为未定义。

4 个答案:

答案 0 :(得分:1)

响应为JSON格式。 您必须使用JSON.parse()

将json转换为javascript对象

答案 1 :(得分:0)

使用JSON.Parse()方法将结果转换为JSON对象。

router.get('/',async (req,res)=>{
    try{
        const results = await Review.findById('some_id')
        const finalResult = JSON.parse(results);
        res.send(finalResult.rating)
    }catch (e){
        res.status(400).send()
    }  
})

答案 2 :(得分:0)

我必须先JSON.stringify()个对象,然后JSON.parse()个对象才能访问其中的键。

const test = JSON.stringify(results)        
const test2 = JSON.parse(test)
console.log(test2.rating)

答案 3 :(得分:-2)

只需将其更改为

router.get('/',async (req,res)=>{
     try{
              const results = await Review.findById('some_id')
              const keys = Object.keys(results)
              res.send(keys)
     }catch (e){
     res.status(400).send()
    }  
})