Mongoose create multiple documents
You can access the variable list of parameters to your callback via arguments
. So you could do something like:
Candy.create(array, function (err) {
if (err) // ...
for (var i=1; i<arguments.length; ++i) {
var candy = arguments[i];
// do some stuff with candy
}
});
With Mongoose v5.1.5, we can use insertMany() method with array passed.
const array = [
{firstName: "Jelly", lastName: "Bean"},
{firstName: "John", lastName: "Doe"}
];
Model.insertMany(array)
.then(function (docs) {
response.json(docs);
})
.catch(function (err) {
response.status(500).send(err);
});
According to this ticket on GitHub, Mongoose 3.9 and 4.0 will return an array if you supply an array and a spread of arguments if you supply a spread when using create()
.