node.js - 如何从猫鼬的嵌套对象数组中删除项目
问题描述
这就是我的“用户”数据库的样子:
{
"_id" : ObjectId("5f1408d3c0e8c130503daafd"),
"username" : "Akhil Jagga",
"data" : [
{
"_id" : ObjectId("5f15cde9329fc9300c7f3843"),
"nameOfList" : "home",
"items" : [
{
"_id" : ObjectId("5f15cde9329fc9300c7f3844"),
"nameOfItem" : "this is the list item"
}
]
},
{
"_id" : ObjectId("5f15cebd9a97051d80c6c6ad"),
"nameOfList" : "personal",
"items" : [
{
"_id" : ObjectId("5f15cebd9a97051d80c6c6ae"),
"nameOfItem" : "this is the list item"
},
{
"_id" : ObjectId("5f15cfd0d73dc330dc8e7fd1"),
"nameOfItem" : "lol"
}
]
}
],
"__v" : 48
}
我想在 nodejs 中使用 mongoose 从“items”数组中删除一个特定对象,比如 ObjectId("5f15cebd9a97051d80c6c6ae")。
我尝试编写以下代码,但它不起作用:
app.post("/delete", redirectLogin, function(req, res) {
const checkedItemId = req.body.checkbox;
const checkedItemName = req.body.hiddenInput;
const listName = req.body.listName;
console.log("item id: " + checkedItemId);
User.findOneAndUpdate(
{
username: req.session.userId
},
{
$pull: {
data: {
items: {
_id: checkedItemId
}
}
}
},
function(err, foundList) {
console.log(foundList);
res.redirect("/");
});
});
- 我尝试使用 findOneAndUpdate,如果我用 id 写项目名称,它会从包含该项目名称和 id 的数据数组中删除整个列表。
感谢您的时间。
解决方案
试试这个,
const username = req.session.userId;
const listName = req.body.listName;
const checkedItemId = req.body.checkbox;
User.update({ "username": username}, { "$pull": { `data.${listName}.items`: { "_id": checkedItemId } }}, { safe: true, multi:true }, function(err, obj) {
//do rest
});
推荐阅读
- laravel - 需要有关在播放器控制器中传递 club_id 的帮助
- asp.net-core - 尝试添加剃须刀组件的向导失败
- partial-views - ASP.NET Core 在使用 @Html.EditorForModel() 时运行多个模板
- c# - 我想获取 SharePoint 列表的列表项(本地),请分享代码以使用 C# 中的属性获取列表项
- react-native - 如何在 react-native 的 createBottomTabNavigator() 中加载自定义选项卡图标
- python - Python Behave - ConfigError:[] 中没有步骤目录
- netlogo - 如何让海龟避免“着陆”补丁,同时仍朝着预定义的目标补丁移动?
- python - 访问在其外部的 WITH 块内声明的变量 - 为什么它有效?
- c# - 当调试器说它们相等时,为什么我的 assert.areequal 会失败?
- spring-boot - 有没有办法从我的 jsp 页面中的 redis 检索数据?