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

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

    Mongoose 4.4 added a method called insertMany

    Shortcut for validating an array of documents and inserting them into MongoDB if they're all valid. This function is faster than .create() because it only sends one operation to the server, rather than one for each document.

    Quoting vkarpov15 from issue #723:

    The tradeoffs are that insertMany() doesn't trigger pre-save hooks, but it should have better performance because it only makes 1 round-trip to the database rather than 1 for each document.

    The method's signature is identical to create:

    Model.insertMany([ ... ], (err, docs) => {
      ...
    })
    

    Or, with promises:

    Model.insertMany([ ... ]).then((docs) => {
      ...
    }).catch((err) => {
      ...
    })
    

提交回复
热议问题