mongodb - Mongoose 从数组数组中删除一个对象
问题描述
我有这样的猫鼬模式:
{
......
project: [
{
Name: String,
Criteria:[
{
criteriaName:String,
}
]
}
]
......
}
我想根据对象ID删除项目数组中的标准数组对象之一
我尝试了以下代码
criteria.findOneAndUpdate({
"_id": uid,
},{ $pull: { "project.Criteria": { _id: cid } } }, (err) => {
......
}
但是这不起作用,它说“不能使用(project.Criteria)的部分(Criteria)来遍历元素”
解决方案
您需要在对数据库的一次查询中完成吗?如果没有,以下解决方案可能对您有用:
criteria.findOne({ _id: uid })
.then((obj) => {
// Filter out the criteria you wanted to remove
obj.project.Criteria = obj.project.Criteria.filter(c => c._id !== cid);
// Save the updated object to the database
return obj.save();
})
.then((updatedObj) => {
// This is the updated object
})
.catch((err) => {
// Handle error
});
对不起,如果 .then/.catch 令人困惑。如有必要,我可以用回调重写,但我认为这看起来更干净。希望这可以帮助!
推荐阅读
- ruby-on-rails - 在“Ruby On Rails API:身份验证”上重现 Auth0 指令时出错
- laravel - Get the sum of polymorphic relationship models multiplied by pivot
- php - zsh:非法硬件指令 PHP mac os 10.15.6
- css - 具有相同代码的网站在开发环境和生产环境之间显示不同的 CSS
- php - 需要帮助使用 Angular 和散列密码阅读/修复 login.php
- python-2.7 - 在 If / Else 语句中将文本存储到标量中 - Robot Framework
- html - HTML 导航栏定位有问题
- php - 托管在 EC2 实例上的 Laravel 项目的站点部署连接被拒绝
- reactjs - MUI:如何将 AppBar 定位在左侧
- html - 如何在输入键上关闭 Angular Material Mat Datepicker Calendar