【问题标题】:NodeJS / Mongoose add Subdocument and update total price and quantityNodeJS / Mongoose 添加子文档并更新总价和数量
【发布时间】: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})

谢谢你:)

【问题讨论】:

    标签: node.js mongoose


    【解决方案1】:

    您可以使用$inc 运算符来原子更新一个文档

    参考$inc operator:

    $inc 运算符将字段增加一个指定的值

    你的操作可能是这样的:

    const cart = await Cart.findByIdAndUpdate(
      {_id: req.session.cart._id}, 
      {
        $push: {courses: req.body},
        $inc: {
          total: parseInt(req.body.price),
          quantity: 1,
        },
      }, 
      {new:true}
    )
    

    【讨论】:

    • 谢谢! :) 这就是我要找的。​​span>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-09
    • 1970-01-01
    • 2022-01-22
    • 2013-03-30
    • 1970-01-01
    • 1970-01-01
    • 2017-04-07
    相关资源
    最近更新 更多