Mostafa Ghadimi
Mostafa Ghadimi

Reputation: 6766

mongoose find one and update function

Suppose that we have a shopping cart in the site, we have specified number of a good in database. Whenever the user wants to validate his/her cart and finalize it, I want to subtract the number of goods that the user purchased from total count of the product. How can I do that?

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
        })
    }

})

Upvotes: 2

Views: 3570

Answers (2)

LittleMygler
LittleMygler

Reputation: 632

You just need to save, and also check for errors.

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

            })
        }

    })

Upvotes: 2

Sridhar
Sridhar

Reputation: 11796

You can use mongoose's findOneAndUpdate() and $inc reference operator with a negative value to decrement the count.

Docs

The following update() operation uses the $inc operator to decrease the quantity field by 2 (i.e. increase by -2) and increase the "metrics.orders" field by 1:

db.products.update(
   { sku: "abc123" },
   { $inc: { quantity: -2, "metrics.orders": 1 } }
)

Making those changes

'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!'
    });
  });

});

Upvotes: 1

Related Questions