[英]Mongoose: Count removed documents
如何检查猫鼬模型的删除方法是否真的删除了某些东西?
MyModel.remove({_id: myId}, function(err, entry) {
if(entry == null) next(new Error("ID was not found.")); // this doesn't work
}
我可以检查删除了多少文件吗?
在Mongo-Documentation kristina1 中写下评论:
如果您在删除后调用 db.runCommand({getLastError:1}) 并且“n”字段将告诉您删除了多少文档。
但我不知道如何用猫鼬做到这一点。
猫鼬 < 4,MongoDB < 3
remove
回调的第二个参数是一个包含删除文档数量的数字。
MyModel.remove({_id: myId}, function(err, numberRemoved) {
if(numberRemoved === 0) next(new Error("ID was not found."));
}
猫鼬 4.x,MongoDB 3.x
传递给remove
回调的第二个参数现在是一个对象,其result.n
字段指示已删除文档的数量:
MyModel.remove({_id: myId}, function(err, obj) {
if(obj.result.n === 0) next(new Error("ID was not found."));
}
我用最新版本的猫鼬试过这个,但没有用。 由于第二个参数作为操作结果返回,而不仅仅是计数。 如下使用,它有效:
Model.remove({
myId: req.myId
}, function(err, removeResult) {
if (err) {
console.log(err);
}
if (removeResult.result.n == 0) {
console.log("Record not found");
}
Console.log("Deleted successfully.");
});
我在 2020 年偶然发现了这一点,并在 Mongoose 5.9.28 中发现结果不再需要结果包装器,因此使用 remove 获取异步方法中已删除记录的计数如下所示:
async function remove(query) { const result = await ItemModel.remove(query); return result.n; }
当然,不推荐使用 collection.remove 以支持 deleteOne 或 deleteMany,所以也试试这个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.