删除多个文档并将其传递给callback

我试图find正确的方式来删除多个文件,以后可以访问它们。

要用一个文档实现这一点,你可以使用findByIdAndRemove或findOneAndRemove ,它们都将find的文档传递给callback函数 。 但是,我没有find任何方法来完成与多个文件。 所以这里是我目前的解决scheme:

Model.find({}, function(err, docs){ // do some stuff with docs // like removing attached uploaded files (avatars, pictures, ...) Model.remove({}, function(err, docs){ // here docs only return the deleted documents' count // i'm unable to perform any kind of operations on docs }) }) 

我想知道是否有更好的方法来做到这一点? 谢谢!

在这种情况下我使用asynchronous和下划线模块。 首先,我为asynchronous创build任务数组,然后并行执行它们。 例如var async = require('async'); var _ = require('underscore');

 Model.find({}, function(err, docs){ // do something var tasks = []; _.each(docs, function(doc){ tasks.push(function(callback){ doc.remove(function(err, removedItem){ callback(err, removedItem); }); }); }); async.parallel(tasks, function(err, results){ // results now is an array of removedItems }); }); 

请参阅https://github.com/caolan/async#parallel和http://mongoosejs.com/docs/api.html#model_Model-remove

ps你可以用本地Array.prototype.forEachreplace下划线。