![](/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.