Mongodb + Node.js:删除多个文档并返回 [英] Mongodb + Node.js: delete multiple documents and return them

查看:156
本文介绍了Mongodb + Node.js:删除多个文档并返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码一次删除多个文档:

I'm using the below code to delete multiple documents at once:

db.collection('testcollection').deleteMany({
    id: {
        $in: ['1', '2', '3']
    }
}, function (error, response) {
    // ...
});

是否可以一次性删除并返回所有已删除的文档?

Is there a way to delete and return all the deleted documents in one go?

注意:我正在寻找 多个删除和多个返回,这与该问题不同:如何在MongoDB中获取已删除的文档?

NOTE: I'm looking for multiple delete and multiple return, which is different than this question: How to get removed document in MongoDB?

推荐答案

不幸的是, deleteMany() 仅传递 deleteWriteOpResult 到您的回调中,因此不会传递任何实际文档.

Unfortunately, deleteMany() passes only the error and deleteWriteOpResult to your callback so no actual documents are passed.

这不仅与Node.js有关-这实际上就是

This is not just with Node.js - this is how actually db.collection.deleteMany works in Mongo:

返回:包含以下内容的文档

Returns: A document containing:

  • 如果布尔值被确认为true 如果运行有写关注,则运行该操作;如果有写关注,则该操作为假 禁用

  • A boolean acknowledged as true if the operation ran with write concern or false if write concern was disabled

deletedCount包含已删除文档的数量

deletedCount containing the number of deleted documents

您必须使用两个请求来完成此操作,但是您可以在一个函数中将其抽象化-例如如果您使用的是本地Mongo驱动程序,可以这样写:

You have to do it with two requests, but you can abstract it away in a single function - e.g. if you're using the native Mongo driver you can write something like this:

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);
        }
      });
    }
  });
}

您可以通过以下方式致电:

that you can call with:

getAndDelete('testcollection', {
    id: {
        $in: ['1', '2', '3']
    }
}, function (error, response) {
    // ...
});

此代码未经测试,只是为了让您知道从哪里开始.

This code is not tested but just to give you an idea where to start from.

注意:曾经有 findAndRemove() ,但已弃用.

Note: there used to be findAndRemove() but it's been deprecated.

这篇关于Mongodb + Node.js:删除多个文档并返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆