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

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

    Use insertMany function to insert many documents. This sends only one operation to the server and Mongoose validates all the documents before hitting the mongo server. By default Mongoose inserts item in the order they exist in the array. If you are ok with not maintaining any order then set ordered:false.

    Important - Error handling:

    When ordered:true validation and error handling happens in a group means if one fails everything will fail.

    When ordered:false validation and error handling happens individually and operation will be continued. Error will be reported back in an array of errors.

提交回复
热议问题