I'm trying to add a subdocument and also update the "total"
and "quanity"
fields of the main document. Right now, I'm doing it like this, but this seems really ugly and inefficient. Is there a better way to achieve this?
// Adds subdocument
const cart = await Cart.findByIdAndUpdate({_id: req.session.cart._id}, {$push: {courses: req.body}}, {new:true})
// Update totals and quantity
cart.set({total: cart.total parseInt(req.body.price), quantity: cart.quantity 1})
await cart.save()
Ideally I would want something like this (the below clearly doesn't work but it's what I'm aiming for logically):
const cart = await Cart.findByIdAndUpdate(req.session.cart._id, async function(err, doc){
if(err){
res.status(404).json({error:err.message})
} else{
doc.courses.push(req.body.course)
doc.total = doc.total parseInt(req.body.price)
doc.quantity = doc.quantity 1
await doc.save()
}
}, {new: true})
Thank you :)
CodePudding user response:
You can use $inc
operator to atomic update one document
refer to $inc operator:
The $inc operator increments a field by a specified value
Your operation could be something like:
const cart = await Cart.findByIdAndUpdate(
{_id: req.session.cart._id},
{
$push: {courses: req.body},
$inc: {
total: parseInt(req.body.price),
quantity: 1,
},
},
{new:true}
)