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

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

    Mongoose doesn't have bulk inserts implemented yet (see issue #723).

    Since you know the number of documents you're saving, you could write something like this:

    var total = docArray.length
      , result = []
    ;
    
    function saveAll(){
      var doc = docArray.pop();
    
      doc.save(function(err, saved){
        if (err) throw err;//handle error
    
        result.push(saved[0]);
    
        if (--total) saveAll();
        else // all saved here
      })
    }
    
    saveAll();
    

    This, of course, is a stop-gap solution and I would recommend using some kind of flow-control library (I use q and it's awesome).

    0 讨论(0)
提交回复
热议问题