node.js - Mongoose:计算删除的文档

标签 node.js mongoose

如何检查 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/

相关文章:

node.js - 加速 Socket.IO

node.js - 如何使用 socket.io、react native、nodejs 管理聊天应用程序的多个套接字连接

javascript - Mongoose 不保存对文档的更改

Mongoose 查询一个填充的字段

node.js - session 管理、Node+Express 和 Mongoose 架构对象

json - 在服务器上存储简单数据,db 还是 json?

mysql - 如何使用expressjs获取表格行复选框选定的数据以发布路线?

javascript - Sequelize + Sequelize 层次结构: How enforce a unique organization name per level?

javascript - 如何使用 Mongoose 从集合中的所有文档中删除字段?

mongodb - 如何按 MongoDB 中嵌入文档的长度进行过滤?