【问题标题】:Get nest object by ID in MongoDB document在 MongoDB 文档中按 ID 获取嵌套对象
【发布时间】:2018-03-30 23:43:31
【问题描述】:

我想检索帖子中的评论以进行编辑。我不确定如何处理这个问题。

这是我的发布文档的样子:

{
    "title" : "First Node.js App",
    "body" : "testing 123",
    "status" : "public",
    "user" : "John Doe",
    "date" : ISODate("2017-12-21T18:30:09.779Z"),
    "comments" : [ 
        {
            "commentBody" : "This is awesome! ",
            "commentUser" : ObjectId("5a3bfd5a9e65351f9c18ba18"),
            "_id" : ObjectId("5a3c02379e65351f9c18ba1a"),
            "commentDate" : ISODate("2017-12-21T18:49:27.620Z")
        },
        {
            "commentBody" : "This is second comment.",
            "commentUser" : ObjectId("5a3bfd5a9e65351f9c18gt19"),
            "_id" : ObjectId("5a3c02379e65351f9c18ba1b"),
            "commentDate" : ISODate("2017-12-21T18:49:27.620Z")
        }
    ],
    "allowComments" : true
}

如何检索评论 ID ObjectId("5a3c02379e65351f9c18ba1a")?

我尝试了以下方法,但没有运气:

const post = await Post.findById(req.params.id);
const comment =  post.comments.find({"_id": req.params.commentid});

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    您需要将回调传递给Array#find:

    const comment = post.comments.find((el) => el._id === req.params.commentid);
    

    【讨论】:

    • 您好 Kristianmitk,感谢您的建议。不幸的是,我在 consle.log(comment) 上得到“未定义”。
    • 我发现了问题,将“el._id === req.params.commentid”更改为“el._id == req.params.commentid”有效。再次感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-17
    • 2021-02-13
    • 1970-01-01
    • 1970-01-01
    • 2011-11-10
    • 1970-01-01
    • 2018-03-09
    相关资源
    最近更新 更多