首页 > 解决方案 > Mongoose 从数组数组中删除一个对象

问题描述

我有这样的猫鼬模式:

{
......
project: [
  {
    Name: String,
    Criteria:[
      {
        criteriaName:String,
      }
    ]
  }
]
......
}

我想根据对象ID删除项目数组中的标准数组对象之一

我尝试了以下代码

criteria.findOneAndUpdate({
    "_id": uid,
},{  $pull: { "project.Criteria": { _id: cid } }  }, (err) => {
......
}

但是这不起作用,它说“不能使用(project.Criteria)的部分(Criteria)来遍历元素”

标签: mongodbmongoose

解决方案


您需要在对数据库的一次查询中完成吗?如果没有,以下解决方案可能对您有用:

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 令人困惑。如有必要,我可以用回调重写,但我认为这看起来更干净。希望这可以帮助!


推荐阅读