【问题标题】:Get value in Object of Mongoose result在 Mongoose 结果的对象中获取值
【发布时间】:2018-08-02 10:59:16
【问题描述】:

我有这样的查询const result = await Form.findOne({ _id: req.params.id });
这是我的查询结果:

{ _id: 5a8ea110d7371b7e5040d5c9,
  _user: 5a5c277f8d82ba3644b971c2,
  formDate: 2018-02-22T10:53:04.579Z,
  formElement: 
   { formName: 'Vanilla Form',
     pixel: '23423325',
     fieldRows: [ [Object], [Object] ] },
  formStyle: 
   { globalColor: [ [Object], [Object], [Object] ],
     elementSizing: 'medium',
     elementStyle: 'radius',
     fontFace: 'Open Sans',
     fontSize: { label: '15', button: '15' } },
  __v: 0,
  status: true }

我正在尝试获得像这样的像素console.log(result.formElement.pixel)
但是,当我尝试获取像素值时,它返回 undefined
怎么了?

更新
这是我的代码:

app.get("/view/:id", async (req, res) => {
    const result = await Form.findOne({ _id: req.params.id });
    console.log(result);
    console.log(result.formDate); //return 2018-02-22T10:53:04.579Z,
    console.log(result.formElement.pixel) //return undefined
    // res.render("form", {
    //  result
    // });
});

我尝试在不使用异步的情况下编辑我的代码,而不是使用 Promise,但它也返回 undefined

【问题讨论】:

  • 调试 result.formElement.formName 并且没有异步等待。
  • 返回TypeError: Cannot read property 'formName' of undefined@StoychoTrenchev

标签: javascript express mongoose


【解决方案1】:

你需要使用exec()函数,它返回promise。

app.get("/view/:id", async (req, res) => {
    let result = await Form.findOne({ _id: req.params.id }).exec();
    result = JSON.parse(JSON.stringify(result));
    console.log(result);
    console.log(result.formDate); //return 2018-02-22T10:53:04.579Z,
    console.log(result.formElement.pixel) //return 23423325
    // res.render("form", {
    //  result
    // });
});

【讨论】:

  • 仍然返回 UnhandledPromiseRejectionWarning:未处理的承诺拒绝(拒绝 id:1):TypeError:无法读取未定义的属性“像素”
  • result = JSON.parse(JSON.stringify(result)) 试试这个。
  • 它工作!你能解释一下为什么我需要使用JSON.parse(JSON.stringify(result)) 吗?
  • mongoose 默认返回文档。检查这个stackoverflow.com/questions/9952649/…
【解决方案2】:

您需要在这里进行一些挖掘。添加更多的 console.logs 来调试实际发生的事情。对于初学者,我建议打印出结果以查看它实际上是什么。我的第一个猜测是您试图在等待完成之前打印结果?我不确定,因为我不知道您何时尝试打印任何内容而没有看到您的代码。

【讨论】:

    猜你喜欢
    • 2013-12-07
    • 2018-01-19
    • 2018-09-22
    • 1970-01-01
    • 2016-12-14
    • 2017-11-19
    • 2018-08-07
    • 2018-06-28
    • 1970-01-01
    相关资源
    最近更新 更多