Reputation: 103
can anyone help me how to add multiple "Addons" per create ? With this code I can add only one addons .. (Tested in postman) but can anyone suggest me how I can make it to add multiple addons ?
Model
const itemSchema = new mongoose.Schema({
name: {
type:String
},
price:{
type:Boolean
},
addons:[{
addonsName:{
type:String
},
price:{
type:String
}
}]
})
Controller :
const addItem = await Item.create({
name:req.body.name,
price: idOfGroup,
addons:[{addonsName:req.body.addonsName, price: req.body.price}]
});
res.status(200).json({status:'Success',addItem})
I "fix" it doing
const addItem = await Item.create(req.body);
And in postman I write
{
"name":"Test1",
"addons" : [
{
"addonsName":"Test",
"price":"100"
},
{
"addonsName":"TestTest",
"price":"200"
}
]
}
But Is this the wrong way of using .Create() ?
Upvotes: 0
Views: 1273
Reputation: 15
you can make the addons as Array like below you can see
const itemSchema = new mongoose.Schema({
name: {
type:String
},
price:{
type:Boolean
},
addons:[]
)}
In controller:
const addItem = await Item.create({
name:req.body.name,
price: idOfGroup,
addons:req.body.addons
});
res.status(200).json({status:'Success',addItem})
Postman request payload:
{
"name":"Test1",
"addons" : [
{
"addonsName":"Test",
"price":"100"
},
{
"addonsName":"TestTest",
"price":"200"
}
]
}
Upvotes: 0
Reputation: 13662
According to your postman sample, you're passing the addons array under the key addons
. So just pass that as the addons:
const addItem = await Item.create({
name: req.body.name,
price: idOfGroup,
addons: req.body.addons,
});
res.status(200).json({ status: "Success", addItem });
You could additionally use object destructuring to get rid of the req.body.
repetition:
const { name, addons } = req.body;
const addItem = await Item.create({
name,
price: idOfGroup,
addons,
});
res.status(200).json({ status: "Success", addItem });
Upvotes: 3