首页 > 解决方案 > MongoDB 使用嵌套在 findOne 中的 .findOneAndUpdate() 与 .updateOne 的不同结果

问题描述

我不确定为什么使用后一种方法无法删除。(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]
}

标签: arraysmongodbmongoose

解决方案


下面的行是错误的,不会工作。这是因为foundList包含查询的结果 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所示进行类型转换。


推荐阅读