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

后端 未结 13 1902
南笙
南笙 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条回答
  •  -上瘾入骨i
    2020-12-07 11:11

    Mongoose does now support passing multiple document structures to Model.create. To quote their API example, it supports being passed either an array or a varargs list of objects with a callback at the end:

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

    Or

    var array = [{ type: 'jelly bean' }, { type: 'snickers' }];
    Candy.create(array, function (err, jellybean, snickers) {
        if (err) // ...
    });
    

    Edit: As many have noted, this does not perform a true bulk insert - it simply hides the complexity of calling save multiple times yourself. There are answers and comments below explaining how to use the actual Mongo driver to achieve a bulk insert in the interest of performance.

提交回复
热议问题