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

后端 未结 13 1904
南笙
南笙 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

    Here is another way without using additional libraries (no error checking included)

    function saveAll( callback ){
      var count = 0;
      docs.forEach(function(doc){
          doc.save(function(err){
              count++;
              if( count == docs.length ){
                 callback();
              }
          });
      });
    }
    

提交回复
热议问题