I have a Mongoose model Product where
var newProduct : {
name : "Product 1",
color : "red",
categoryId : 1023,
isAvailbale : true
}
var mongooseProductModel = new products(newProduct);
With Mongoose with everything setup I can save Product by calling
mongooseProductModel.save(function(err)){
}
This works fine when I want to create one product only. But what if I want to create multiple products at one shot? Like in entity framework we can submit a collection of entities to the DBContext and calling save will save all entities with a single save product call. Is it possible to achieve that with Mongoose?
i think you can call asynchronous save function. This is example of code, that prepopulates the database with data from JSON object https://github.com/vodolaz095/hunt/blob/master/examples/lib/populateDatabase.js
var preys = [
{
'name': 'Alan Schaefer',
'scored': false,
'priority': 10
},
{
'name': 'George Dillon',
'scored': true,
'priority': 9
},
{
'name': 'Rick Hawkins',
'scored': true,
'priority': 8
},
{
'name': 'Blain Cooper',
'scored': true,
'priority': 7
},
{
'name': 'Billy Sole',
'scored': true,
'priority': 6
},
{
'name': 'Anna Goncalves',
'scored': false,
'priority': 0
},
];
module.exports = exports = function (hunt) {
//populating the trophies' collection in database
hunt.model.Trophy.remove({}, function (error) {
if (error) {
throw error;
} else {
hunt.async.map(preys, function (prey, cb) {
hunt.model.Trophy.create(prey, cb);
}, function (error, preysSaved) {
if (error) {
throw error;
} else {
console.log('' + preysSaved.length + ' trophies recorded.');
}
});
}
});
};
this code works via the https://github.com/caolan/async#map function.
so, you can call the function via map on array of JSON objects, and the iterator function will create the mongoose entity from each of thems