【问题标题】:Retrieving object properties from the result fetched from mongodb in nodejs从nodejs中从mongodb获取的结果中检索对象属性
【发布时间】:2018-08-23 22:52:42
【问题描述】:

我正在尝试检索对象属性数组,但除了对象中的 _id 之外,我无法检索任何属性。但是我可以一次检索整个数组,甚至可以检索数组中的单个对象,但不能检索每个对象中的属性。

这是 JSON 结构

[{
   "_id": "5a82df96f2730d4bb177ffe1",
   "project_id": 123,
   "project_name": "proj11",
   "tasks": [],
   "links": [],
   "__v": 0,
   "upsert": true
}]

这是代码

taskDelay(req,res) {
    ProjectMaster.find({ "project_id": 123 })
    .then(response => {
        var result = response[0];
        var resultId = response[0]._id;
        var resultName = response[0].project_name;
        var resultProjId = response[0].project_id;
        console.log(result);           // outputs the object
        console.log(resultId);         // outputs 5a82df96f2730d4bb177ffe1
        console.log(resultName);       // undefined
        console.log(resultProjId);     // undefined
        res.status(200).send(response)
    })
    .catch(error => res
        .status(400)
        .send(error));
}

其他属性显示未定义的原因可能是什么??

【问题讨论】:

  • 你能给出console.log(response[0])的输出吗?
  • { "_id": "5a82df96f2730d4bb177ffe1", "project_id": 123, "project_name": "proj11", "tasks": [], "links": [], "__v": 0, "upsert": true } 它正在按预期输出第一个对象
  • 您可以编辑您的帖子以包含您的 ProjectMaster 架构(或在此处发布)吗?
  • const ProjectMasterSchema=new Schema({},{strict: false}); 这是项目主架构
  • 查看您的代码和 cmets 我找不到发生这种情况的原因。建议你把var改成let再运行看看会发生什么

标签: json node.js mongodb express mongoose


【解决方案1】:

最后,我找到了解决这个问题的方法。它使用 mongodb 作为响应发送的数据格式。我试图做 JSON.parse 但它没有用。 toObject() 成功了。

taskDelay(req,res) {
ProjectMaster.find({ "project_id": 123 })
.then(response => {
    var result = response[0];
    var resultId = response[0]._id;
    var resultName = response[0].toObject().project_name;
    var resultProjId = response[0].toObject().project_id;
    console.log(result);           // outputs the object
    console.log(resultId);         // outputs 5a82df96f2730d4bb177ffe1
    console.log(resultName);       // outputs 123
    console.log(resultProjId);     // outputs proj11
    res.status(200).send(response)
})
.catch(error => res
    .status(400)
    .send(error));
}

我犯了一个错误,没有完全阅读 mongoose 文档!此行为与 mongoose 数据格式有关。

【讨论】:

    猜你喜欢
    • 2015-12-15
    • 1970-01-01
    • 2018-11-21
    • 2016-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-27
    相关资源
    最近更新 更多