updating product quantity in Stock after ordering in order collection,MongoDB and Nodejs

Issue

I am working on an inventory system management using MongoDB,ExpressJs,ReactJs,Express, and my question is – how I can update a product quantity after completing it’s order?

let me explain: if the product quantity in stock is 10 for example,then after ordering like 3 ,I want the product quantity to be 7 directly…

Solution

const createOrder = asyncHandler(async(req, res) =>{
    const user = await User.findById(req.user.id)
    if(!user || user.isAdmin === false){
        res.status(401)
        throw new Error('No Authorised')
    }
    const {
        customerName,
        customerAddress,
        customerNumber,
        orderItems,
        totalPrice
    } = req.body

    if(orderItems && orderItems.length === 0){
        res.status(400)
        throw new Error('No order Items')
    }
    else{
        const order = new Order({
            customerName,
            customerAddress,
            customerNumber,
            orderItems,
            totalPrice,
            user,
        })
        const createdOrder = await order.save()
        orderItems.forEach((item) => {
            Product.updateOne(
            {_id: _id},
            {$inc: {qteInStock: -orderItems.quantity}},
            (err, updatedData) => {})
        }
        res.status(200).json(createdOrder)
    }

})

I didn’t find from where you are taking the _id to update the products collection.
And orderItems is an array so you won’t get quantity inside of it.

You have to loop through each item of orderItems and update the collection.

Note :
send the response once after the complete process.
In the code, you sent before updating the quantity, I have changed the above code with whatever I could do.

Answered By – sachin

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published