skip to Main Content
      app.put('/product/:id', async(req, res) =>{
        const id = req.params.id;
        const updateQuantity = req.body;
        const filter = {_id: ObjectId(id)};
        const options = { upsert: true};
        const updateDoc = {
            $set: {
                productQuantity: updateQuantity.productQuantity
            }
        };
        const result = await productCollection.updateOne(filter, updateDoc, options);
        res.send(result);

    })

//this code only can replace the quantity can’t increase or decrease the quantity.

2

Answers


  1. You can try the increment operator $inc along with findOneAndUpdate. The code would change as follows:

    app.put('/product/:id', async (req, res) => {
        const id = req.params.id;
        const updateQuantity = req.body;
        const filter = { _id: ObjectId(id) };
        const options = { upsert: true };
        const updateDoc = {$inc : {'productQuantity' : 1}};
        const result = await productCollection.findOneAndUpdate(filter, updateDoc, options).exec()
        res.send(result);
    });
    

    To decrease the value:
    const updateDoc = {$inc : {'productQuantity' : -1}};

    Login or Signup to reply.
  2. To increase the count by 5.

    const updateDoc ={
        $inc: {
            productQuantity: 5
        }
    };
    

    To Decrement the count by 5

    const updateDoc ={
        $inc: {
            productQuantity: -5
        }
    };
    

    Now make sure the value passed to the productQuantity is a Number and not a string. You can do that by passing updateQuantity.productQuantity in Number constructor like

    
    const productQuantity = Number(updateQuantity.productQuantity)
    
    // increment
    const updateDoc ={
        $inc: {
            productQuantity: productQuantity,
        }
    };
    
    // decrement
    const updateDoc ={
        $inc: {
            productQuantity: productQuantity * -1
        }
    };
    
    

    PS: product.productQuantity is a bad name. Try product.quanlity next time.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search