I\'ve been researching this question to no-ends, but can\'t find the simple answer I\'m looking for. Basically, I\'d like to batch POST JSON objects in array.
I\'ve
If you send you array as a key in your request body, something like this
You'll get it as req.body.my_restaurants. Then simply use this :
db.collection('restaurants').insertMany(req.body.my_restaurants, function(err, restaurants){
if(err) console.log(err);
else console.log("restaurants Added Successfully");
});
I'm assuming that restaurants is the name of your collection.
I've been playing with the previous solution I marked as correct. An even better approach than using the .insertMany() function is to use the .create() function.
The .insertMany() function skips the middleware associated with .save(), whereas the create() function uses the same process, but can also handle arrays.
So my modified express route looked like the below (where Organization is the name of my schema):
app.post('/api/orgs', function(req, res) {
// Array of JSON Objects
if (req.body.batch){
Organization.create(req.body.batch, function(err){
if(err)
res.send(err);
else
res.json(req.body);
});
}
// Single JSON Object
else {
var newOrg = new Organization(req.body);
// New User is saved in the db.
newOrg.save(function(err){
if(err)
res.send(err);
// If no errors are found, it responds with a JSON of the new user
else
res.json(req.body);
});
}
});
And I'm sending JSON objects that look like:
Hope this helps someone else down the line.