如何检查 Mongoose 模型的 remove-method 是否确实删除了某些内容?
MyModel.remove({_id: myId}, function(err, entry) {
if(entry == null) next(new Error("ID was not found.")); // this doesn't work
}
我可以查看删除了多少文档吗?
在 Mongo-Documentation Kristina1 在评论中写道:
If you call db.runCommand({getLastError:1}) after a remove and the "n" field will tell you how many documents were deleted.
但我不知道如何用 Mongoose 做到这一点。
最佳答案
Mongoose < 4,MongoDB < 3
remove
回调的第二个参数是一个数字,包含删除的文档数。
MyModel.remove({_id: myId}, function(err, numberRemoved) {
if(numberRemoved === 0) next(new Error("ID was not found."));
}
Mongoose 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."));
}
关于node.js - Mongoose:计算删除的文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12007017/