【问题标题】:MongoDB Different result using .findOneAndUpdate() vs .updateOne nested in findOneMongoDB 使用嵌套在 findOne 中的 .findOneAndUpdate() 与 .updateOne 的不同结果
【发布时间】:2021-04-05 19:07:43
【问题描述】:

我不确定为什么使用后一种方法无法进行删除。 (foundList 不是null

后一种方法:

    List.findOne({name: listType}, function(err, foundList){
      if (err){
        console.log(err);
      } else {
        foundList.updateOne({}, { $pull: { item: { _id: itemID } } });
        console.log('deletion success');
        res.redirect("/" + listType);
      }
    });
  }

架构:

const itemSchema = {text: String}
const listSchema = {  
  name: String,
  item: [itemSchema]
}

【问题讨论】:

  • findOneAndUpdateupdateOne 得到不同的结果是因为如果选项 { new: true} 未作为第三个参数传递给 API,findOneAndUpdate 将返回旧文档。

标签: arrays mongodb mongoose


【解决方案1】:

下面的行是错误的,不会工作。这是因为foundList 包含result of the query findOne

foundList.updateOne({}, { $pull: { item: { _id: itemID } } });

调用List.findOne({name: listType}, function(err, foundList) 后,foundList 包含查询的结果,您不能在其上调用任何查询/mongoose-api。您需要在模型对象上调用 updateOne 之类的 mongoose API,然后才能得到结果。

您可以做的是修改该文档,然后将其保存。你可以这样做:

List.findOne({name: listType}, function(err, foundList){
      if (err){
        console.log(err);
      } else {
        let index = foundList.findIndex((list: any) => list.item._id == itemID );
        if (index !== -1) {
            foundList.splice(index, 1);
        }
        foundList.save().then(()=>{
            console.log('deletion success');
            res.redirect("/" + listType);
        })
     }
})

或者您可以在一个查询中完成所有这些操作。试试这个:

List.findOneAndUpdate({name: listType}, {
   $pull: {
       item: { _id: itemID } 
   }, {new:true})
.then((response) => {
   console.log('deletion success');
   res.redirect("/" + listType);
})
.catch((err) => res.json(err));

注意:还要确保 itemID 的类型为 ObjectId 而不是 string。您可以将string 类型转换为ObjectId,如图所示here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-12
    • 2022-12-09
    • 2017-12-14
    • 1970-01-01
    • 2018-05-09
    • 2018-03-01
    • 2021-05-29
    • 1970-01-01
    相关资源
    最近更新 更多