很遗憾,deleteMany() http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#deleteMany仅通过error http://mongodb.github.io/node-mongodb-native/2.2/api/MongoError.html and 更新写操作结果 http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~deleteWriteOpResult到您的回调,因此不会传递任何实际文档。
这不仅仅是 Node.js 的问题——实际上就是这样db.collection.deleteMany https://docs.mongodb.com/v3.2/reference/method/db.collection.deleteMany/在蒙戈工作:
返回:包含以下内容的文档:
您必须通过两个请求来完成此操作,但您可以将其抽象为单个函数 - 例如如果你正在使用原生 Mongo 驱动 http://mongodb.github.io/node-mongodb-native/2.2/api/index.html你可以写这样的东西:
function getAndDelete(collectionName, filter, callback) {
var collection = db.collection(collectionName);
collection.find(filter, function (err, data) {
if (err) {
callback(err);
} else {
collection.deleteMany(filter, function (err, r) {
if (err) {
callback(err);
} else {
callback(null, data);
}
});
}
});
}
您可以通过以下方式致电:
getAndDelete('testcollection', {
id: {
$in: ['1', '2', '3']
}
}, function (error, response) {
// ...
});
该代码未经测试,只是为了让您了解从哪里开始。
注:以前有findAndRemove() http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#findAndRemove但它已被弃用。