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

Time:09-06

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

hope someone understand the logic

waiting for your help

CodePudding user response:

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.

Hope this helps you! Please comment if you get any errors or are stuck with anything in this.

CodePudding user response:

this is how my function looks like but it's not working

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()
        res.status(200).json(createdOrder)
        await Product.updateOne(
            {_id: _id},
            {$inc: {qteInStock: -orderItems.quantity}},
            (err, updatedData) => {}
        )
    }

})
  • Related