Reputation: 149
Current code can save single data. I have multiple data at incoming request. How can i save the multiple data to mongodb? As you can see in the image there are 3 different objects.
Orders route
router.route("/api/orders").post((req, res) => {
const body = req.body;
console.log(body);
const orderid = req.body.id;
const ordername = req.bodyname;
const orderdescription = req.bodydescription;
const orderquantity = req.bodyquantity;
const ordertotalprice = req.bodytotalPrice;
const newOrder = new Orders({
orderid,
ordername,
orderdescription,
orderquantity,
ordertotalprice
});
newOrder
.save()
.then(() => {
console.log("Order Added!");
res.status(200).json("Order Added!");
})
.catch(err => res.status(400).json("Error: " + err));
});
module.exports = router;
Upvotes: 1
Views: 2291
Reputation: 17858
Your request body is an array of objects.
You can use Model.insertMany() method to insert multiple documents. Before using insertMany be sure, you convert the objects in request body to the mongoose model object correctly. Here I used javascript map method to show a sample, you may need to change that transformation.
router.route("/api/orders").post((req, res) => {
const body = req.body;
console.log(body);
let items = req.body.map(item => {
return {
orderid: item.id,
ordername: item.name,
orderdescription: item.description,
orderquantity: item.quantity,
ordertotalprice: item.totalPrice
};
});
Orders.insertMany(items)
.then(() => {
console.log("Orders Added!");
res.status(200).json("Order Added!");
})
.catch(err => res.status(400).json("Error: " + err));
});
module.exports = router;
Upvotes: 1