【发布时间】:2022-01-18 07:30:09
【问题描述】:
我正在尝试添加子文档并更新主文档的 "total" 和 "quanity" 字段。现在,我正在这样做,但这看起来真的很丑陋且效率低下。有没有更好的方法来实现这一点?
// 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()
理想情况下,我想要这样的东西(以下显然行不通,但这是我在逻辑上的目标):
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})
谢谢你:)
【问题讨论】: