![](/img/trans.png)
[英]How to push a nested array of object to another object as a nested array of objects? (MongoDB/NodeJS)
[英]How can I push an object to a nested array of objects in mongoDB and expressjs
我有以下 Board 对象:
{
"boardMembers": [
"5f636a5c0d6fa84be48cc19d"
],
"boardLists": [
{
"cards": [],
"_id": "5f6387e077beba2e3c15d15a",
"title": "list one",
"__v": 0
}
],
"_id": "5f63877177beba2e3c15d159",
"boardName": "board1",
"boardPassword": "123456",
"boardCreator": "5f636a5c0d6fa84be48cc19d",
"g_createdAt": "2020-09-17T15:57:37.616Z",
"__v": 2
}
如您所见,有一个“boardLists”数组,我想发出一个发布请求,将卡片发布到该数组中具有特定 ID 的列表中。
我的代码:
router.post("/add-task/:id", auth, boardAuth, async (req, res) => {
const listId = req.params.id;
try {
const board = await Board.findOne({ _id: req.board._id });
if (!board) return res.status(404).send("no such board");
const list = await List.findOne({ _id: listId });
if (!list) return res.status(404).send("List not found");
const task = new Task({
text: req.body.text,
});
Board.updateOne(
{ _id: req.board._id, "boardLists._id": listId },
{ $push: { "boardLists.$.cards": task } }
);
await board.save();
res.send(board);
} catch (err) {
console.log(err);
}
});
现在的问题是,当我在邮递员中进行请求调用时,它会在我想要的特定列表中进行推送,但不会将推送保存在父板对象中:当对该对象发出 get 请求时,我会得到一个空的卡片数组。 像那样:
{
"boardMembers": [
"5f636a5c0d6fa84be48cc19d"
],
"boardLists": [
{
"cards": [],
"_id": "5f6387e077beba2e3c15d15a",
"title": "list one",
"__v": 0
}
],
"_id": "5f63877177beba2e3c15d159",
"boardName": "board1",
"boardPassword": "123456",
"boardCreator": "5f636a5c0d6fa84be48cc19d",
"g_createdAt": "2020-09-17T15:57:37.616Z",
"__v": 2
}
为什么它不保存在板对象中的推送?
猫鼬很奇怪。 您需要将该字段标记为已修改,否则将不会保存更改。 尝试这个 :
board.markModified("boardLists");
await board.save();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.