node.js - 如何使用 express js 更新猫鼬数组?
问题描述
所以我有以下文档,它是一个包含任务列表的板(如待办事项列表)
{
"boardMembers": [
"5f636a5c0d6fa84be48cc19d",
],
"boardLists": [
{
"cards": [
{
"_id": "5f7c9b77eb751310a41319ab",
"text": "task one"
},
{
"_id": "5f7c9bb524dd8d42d469bba3",
"text": "task two"
}
],
"_id": "5f7c9b6b02c19f21a493cb7d",
"title": "List one",
"__v": 0
}
],
"_id": "5f63877177beba2e3c15d159",
"boardName": "board1",
"boardPassword": "123456",
"boardCreator": "5f636a5c0d6fa84be48cc19d",
"g_createdAt": "2020-09-17T15:57:37.616Z",
"__v": 46
}
如何更新和删除其中一张卡片?(我没有任务架构,我想从董事会文档中删除任务
我试过这个:
router.put("/delete-task/:list/:task", auth, boardAuth, async (req, res) => {
const listId = req.params.list;
const task = req.params.task;
const board = await Board.findOne({ _id: req.board._id });
if (!board) return res.status(404).send("no such board");
Board.findOneAndUpdate(
{ _id: req.board._id },
{ $pull: { "boardLists.$[outer].cards": { _id: task } } },
{
arrayFilters: [{ "outer._id": listId }],
}
);
res.send(board);
});
解决方案
使用过滤的位置运算符来标识与更新$[<identifier>]
匹配的数组元素。arrayFilters
用于更新cards
数组中的对象:
Board.findOneAndUpdate(
{ _id: "boardId" },
{ $set: { "boardLists.$[outer].cards.$[inner].text": "update value" } },
{
arrayFilters: [
{ "outer._id": "boardListId" },
{ "inner.text": "task two" },
]
}
);
用于删除cards
数组使用中的对象$pull
Board.findOneAndUpdate(
{ _id: "boardId" },
{ $pull: { "boardLists.$[outer].cards": { text: "task two" } } },
{
arrayFilters: [{ "outer._id": "boardListId" }],
}
);