arrays - 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]
}
解决方案
下面的行是错误的,不会工作。这是因为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
所示进行类型转换。
推荐阅读
- java - 列表 API 按流 API 分组
- flutter - 从休息调用中获取地图结果列表
- python-3.x - WebDriverException:消息:未知错误:调用函数结果缺少“值”——在运行 send_keys 并更新 Chromedriver 之后
- java - 我应该在 Spring Boot REST API 中发布什么对象?
- javascript - Javascript 19位数字将最后一位数字更改为零
- python - 如何将 Discord.py 和 Flask 合并到一个文件中?
- google-sheets - 结束时间戳跨到午夜的 2 个时间戳之间的 Google 表格持续时间
- axios - Axios 发送带有参数的 url 作为字符串而不是对象
- mongodb - $elemMatch 相当于嵌套数组 com.mongodb.client.model.Filters.elemMatch
- javascript - 将 React Context API 类转换为 Hook 的函数