Node.js mongoose查找并更新函数

Node.js mongoose查找并更新函数,node.js,mongoose,Node.js,Mongoose,假设我们在站点中有一个购物车,我们在数据库中指定了一个商品的数量。每当用户想要验证他/她的购物车并完成它时,我想从产品总数中减去用户购买的商品数量。我该怎么做 router.post('/done', (req, res) => { // substract from the count for (var i = 0; i < req.body.cart.length; i++){ Product.findOne({_id: req.body.cart

假设我们在站点中有一个购物车,我们在数据库中指定了一个商品的数量。每当用户想要验证他/她的购物车并完成它时,我想从产品总数中减去用户购买的商品数量。我该怎么做

router.post('/done', (req, res) => {
    // substract from the count
    for (var i = 0; i < req.body.cart.length; i++){
        Product.findOne({_id: req.body.cart[i]._id}).exec((err, result) => {
            result.count = result.count - req.body.cart[i].count;
            // update the value of result.count and save it on database
        })
    }

})
router.post('/done',(req,res)=>{
//从计数中减去
对于(变量i=0;i{
result.count=result.count-req.body.cart[i].count;
//更新result.count的值并将其保存在数据库中
})
}
})
您可以使用mongoose和
$inc
参考运算符来减少计数

文档

下面的update()操作使用$inc运算符将数量字段减少2(即增加-2),并将“metrics.orders”字段增加1:

做出这些改变

'use strict';

router.post('/done', (req, res) => {

  let {cart} = req.body;

  if (!Array.isArray(cart) || cart.length === 0) {
    return res.status(400).send({
      msg: 'Empty cart'
    });
  }

  let updates = cart.map(item => {
    return Product.findOneAndUpdate({
      _id: item._id
    }, {
      $inc: {
        count: -1 * item.count
      }
    }, {
      upsert: false
    });
  });

  Promise.all(updates).then(() => {
    return res.status(200).send({
      msg: 'inventory updated'
    });
  }).catch(err => {
    console.log('err', err.stack);
    return res.status(500).send({
      msg: 'inventory update failed!'
    });
  });

});

您只需要保存,还需要检查错误

router.post('/done', (req, res) => {
        // substract from the count
        for (var i = 0; i < req.body.cart.length; i++){
            Product.findOne({_id: req.body.cart[i]._id}).exec((err, result) => {
                if(result)
                {
                 result.count = result.count - req.body.cart[i].count;
                 result.save((err) => {
                  if (err) // do something
                 });
                }
                //If you don't find the product for some reason, do something

            })
        }

    })
router.post('/done',(req,res)=>{
//从计数中减去
对于(变量i=0;i{
如果(结果)
{
result.count=result.count-req.body.cart[i].count;
结果。保存((错误)=>{
如果(错误)//做某事
});
}
//如果你因为某种原因找不到产品,那就做点什么吧
})
}
})
router.post('/done', (req, res) => {
        // substract from the count
        for (var i = 0; i < req.body.cart.length; i++){
            Product.findOne({_id: req.body.cart[i]._id}).exec((err, result) => {
                if(result)
                {
                 result.count = result.count - req.body.cart[i].count;
                 result.save((err) => {
                  if (err) // do something
                 });
                }
                //If you don't find the product for some reason, do something

            })
        }

    })