Mongoose create multiple documents

Solution 1:

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

Solution 2:

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

Solution 3:

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().

Solution 4:

Since Mongoose v5 you can use insertMany According to the mongoose site it is faster than .create():

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.

Complete example:

const mongoose = require('mongoose'); 
  
// Database connection 
mongoose.connect('mongodb://localhost:27017/databasename', { 
    useNewUrlParser: true, 
    useCreateIndex: true, 
    useUnifiedTopology: true
}); 
  
// User model 
const User = mongoose.model('User', { 
    name: { type: String }, 
    age: { type: Number } 
}); 


// Function call, here is your snippet
User.insertMany([ 
    { name: 'Gourav', age: 20}, 
    { name: 'Kartik', age: 20}, 
    { name: 'Niharika', age: 20} 
]).then(function(){ 
    console.log("Data inserted")  // Success 
}).catch(function(error){ 
    console.log(error)      // Failure 
});