node.js 猫鼬查找和删除

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31662783/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 19:09:34  来源:igfitidea点击:

Mongoose Find and Remove

node.jsmongodbmongoosedatabase

提问by Micha Schwab

I'm trying to delete multiple documents that satisfy a query. However I need the data of those documents for storing them in a separate collection for undo functionality. The only way I got this to work is with multiple queries:

我正在尝试删除满足查询的多个文档。但是,我需要将这些文档的数据存储在单独的集合中以实现撤消功能。我让它工作的唯一方法是使用多个查询:

Data.find(query).exec(function(err, data)
{
    Data.remove(query).exec(function(err2)
    {
        ActionCtrl.saveRemove(data);
    });
});

Is there a better way? In this post: How do I remove documents using Node.js Mongoose?it was suggested to use find().remove().exec():

有没有更好的办法?在这篇文章中:如何使用 Node.js Mongoose 删除文档?建议使用 find().remove().exec():

Data.find(query).remove().exec(function(err, data)
{
    ActionCtrl.saveRemove(data);
});

However datais usually 1, don't ask me why. Can I do this without infinitely nesting my queries? Thanks!

但是data通常是1,不要问我为什么。我可以在不无限嵌套查询的情况下执行此操作吗?谢谢!

回答by snozza

As you have noted, using the following will not return the document:

正如您所指出的,使用以下内容不会返回文档:

Data.find(query).remove().exec(function(err, data) {
  // data will equal the number of docs removed, not the document itself
}

As such, you can't save the document in ActionCtrlusing this approach.

因此,您无法ActionCtrl使用此方法保存文档。

You can achieve the same result using your original approach, or use some form of iteration. A control flow library like asyncmight come in handy to handle the async calls. It won't reduce your code, but will reduce the queries. See example:

您可以使用原始方法或使用某种形式的迭代来获得相同的结果。像async这样的控制流库可能会派上用场来处理异步调用。它不会减少您的代码,但会减少查询。见示例:

Data.find(query, function(err, data) {
  async.each(data, function(dataItem, callback) {
    dataItem.remove(function(err, result) {
      ActionCtrl.saveRemove(result, callback);
    });
  });
});

This answer assumes that the ActionCtrl.saveRemove()implementation can take an individual doc as a parameter, and can execute the callback from the async.eachloop. async.eachrequires a callback to be run without arguments at the end of each iteration, so you would ideally run this at the end of .saveRemove()

这个答案假设ActionCtrl.saveRemove()实现可以将单个文档作为参数,并且可以从async.each循环中执行回调。async.each需要在每次迭代结束时不带参数地运行回调,因此您最好在结束时运行它.saveRemove()

Note that the removemethod on an individual document will actually return the document that has been removed.

请注意,remove单个文档上的方法实际上将返回已删除的文档。