Node.js – Mongoose create multiple documents

mongoosenode.js

I know in the latest version of Mongoose you can pass multiple documents to the create method, or even better in my case an array of documents.

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

My problem is that the size of the array is dynamic so in the callback it would be helpful to have an array of the created objects.

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

    candies.forEach(function(candy) {
       // do some stuff with candies
    });
});

Not in the documentation, but is something like this possible?

Best Solution

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
    }
});