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

Viewed 49

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...

2 Answers

You have to write separate your own logic for this however I can share the common logic which can be used.

Let's say you store the products in this way ( example ) : {product : 'apple', quantity : 10, productId : 121 }

then,

Once you receive new order, use the product name or productId ( I suggest using productId ), use

products.findOneAndUpdate({ productId : productId }, $inc: {quantity : ( 0 - orderQuantity) }, (err, updatedData) => {})

Here you might have to change the products.findOneAndUpdate to products.updateOne based on whether you are using mongoose or MongoDB.

also productId is the productId you received from the request.
And orderQuantity is the quantity of the orders.

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.

Related