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

后端 未结 13 1930
南笙
南笙 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:49

    Use async parallel and your code will look like this:

      async.parallel([obj1.save, obj2.save, obj3.save], callback);
    

    Since the convention is the same in Mongoose as in async (err, callback) you don't need to wrap them in your own callbacks, just add your save calls in an array and you will get a callback when all is finished.

    If you use mapLimit you can control how many documents you want to save in parallel. In this example we save 10 documents in parallell until all items are successfully saved.

    async.mapLimit(myArray, 10, function(document, next){
      document.save(next);
    }, done);
    

提交回复
热议问题