Mongoose 在嵌套对象上找到一个

Lin*_*inx 2 mongoose mongodb node.js

我正在尝试从嵌套在 Mongo 对象中的对象获取信息。数据结构如下所示:

Card{
    _id;
    contributors: [
        {
            name;
            _id;
        },
        {
            name;
            _id;
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

这是我尝试访问“贡献者”数组中的特定“贡献者”。

Card.findOne({_id: cardId, "contributor._id": contributorId},
    (err, contributor) => {
        if (err) {
            console.log(err);
            res.status(500);
            res.send({status: "error", message: "sass overload"});
            return;
        }
    console.log(contributor);
    res.send(contributor);
});
Run Code Online (Sandbox Code Playgroud)

Mar*_*rkB 5

你需要使用"contributors._id""contributor._id"

您模型中的字段名称contributors不是contributor. 很明显,但要注意。

  • 但这就是答案。不久前我也遇到了类似的问题。 (2认同)