【问题标题】:Mongoose remove one object from array of arrayMongoose 从数组数组中删除一个对象
【发布时间】:2019-02-04 22:41:53
【问题描述】:

我有这样的 Mongoose 架构:

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

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

我尝试了以下代码

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

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

【问题讨论】:

  • 必须是{ $pull: { "project.$.Criteria": { _id: cid } } }
  • @AnthonyWinzlet 上面说的是The positional operator did not find the match needed from the query. 不知道能不能在数组数组中工作
  • 你的mongodb版本是多少?

标签: mongodb mongoose


【解决方案1】:

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

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

【讨论】:

  • 是的,我想在一次查询数据库中做到这一点,使其看起来干净高效,但您的代码看起来很干净
猜你喜欢
  • 1970-01-01
  • 2019-10-23
  • 2018-04-26
  • 2016-03-16
  • 2021-07-27
  • 1970-01-01
  • 1970-01-01
  • 2015-06-19
  • 1970-01-01
相关资源
最近更新 更多