How can I save multiple documents concurrently in Mongoose/Node.js?

后端 未结 13 1915
南笙
南笙 2020-12-07 10:20

At the moment I use save to add a single document. Suppose I have an array of documents that I wish to store as single objects. Is there a way of adding them all with a si

13条回答
  •  暖寄归人
    2020-12-07 10:52

    You can use the promise returned by mongoose save, Promise in mongoose does not have all, but you can add the feature with this module.

    Create a module that enhance mongoose promise with all.

    var Promise = require("mongoose").Promise;
    
    Promise.all = function(promises) {
      var mainPromise = new Promise();
      if (promises.length == 0) {
        mainPromise.resolve(null, promises);
      }
    
      var pending = 0;
      promises.forEach(function(p, i) {
        pending++;
        p.then(function(val) {
          promises[i] = val;
          if (--pending === 0) {
            mainPromise.resolve(null, promises);
          }
        }, function(err) {
          mainPromise.reject(err);
        });
      });
    
      return mainPromise;
    }
    
    module.exports = Promise;
    

    Then use it with mongoose:

    var Promise = require('./promise')
    
    ...
    
    var tasks = [];
    
    for (var i=0; i < docs.length; i++) {
      tasks.push(docs[i].save());
    }
    
    Promise.all(tasks)
      .then(function(results) {
        console.log(results);
      }, function (err) {
        console.log(err);
      })
    

提交回复
热议问题