猫鼬从阵列的阵列中删除一个对象

问题描述 投票:0回答:1

我有猫鼬的模式是这样的:

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

我想根据对象ID删除标准阵列的对象是项目阵列中的一个

我想下面的代码

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

然而,这不能正常工作,它说:“无法使用的(project.Criteria)的部分(标准)横贯元件”

mongodb mongoose
1个回答
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
});

很抱歉,如果在。于是/ .catch是混乱的。我可以回调,必要时重写,但我觉得这看起来很干净。希望这可以帮助!

© www.soinside.com 2019 - 2024. All rights reserved.