猫鼬从数组数组中删除一个对象

时间:2019-02-01 14:23:56

标签: mongodb mongoose

我有这样的猫鼬模式:

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

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

我尝试了以下代码

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

但是这无法正常工作,它说“无法使用(project.Criteria)的部分(Criteria)遍历元素”

1 个答案:

答案 0 :(得分:0)

您是否需要对数据库进行一次查询?如果没有,以下解决方案可能对您有用:

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

相关问题