Mongoose (mongodb) batch insert?

后端 未结 8 1981
灰色年华
灰色年华 2020-11-27 10:15

Does Mongoose v3.6+ support batch inserts now? I\'ve searched for a few minutes but anything matching this query is a couple of years old and the answer was

8条回答
  •  感情败类
    2020-11-27 10:37

    Indeed, you can use the "create" method of Mongoose, it can contain an array of documents, see this example:

    Candy.create({ candy: 'jelly bean' }, { candy: 'snickers' }, function (err, jellybean, snickers) {
    });
    

    The callback function contains the inserted documents. You do not always know how many items has to be inserted (fixed argument length like above) so you can loop through them:

    var insertedDocs = [];
    for (var i=1; i

    Update: A better solution

    A better solution would to use Candy.collection.insert() instead of Candy.create() - used in the example above - because it's faster (create() is calling Model.save() on each item so it's slower).

    See the Mongo documentation for more information: http://docs.mongodb.org/manual/reference/method/db.collection.insert/

    (thanks to arcseldon for pointing this out)

提交回复
热议问题