Categories
Development MongoDB

How to write MongoDb Mongoose query to match two attributes

My Stock Model file looks something like this :

const Stock = new Schema(
    {
        ClientId : {type : Schema.ObjectId},
        ClientName : {type : String}, 
        StockName : { type : String },
        StockType : { type : String },      
        ConsumedQuantity : {type : Number},
        TotalQuantity : {type : Number},
        WastageQuantity : {type : Number}, 

     },
    { timestamps: true },
);

Also here’s a query from my stock controller :

Stock.findOne({ ClientId : clientId }, (err, stock) => {


        if (err) {
            return res.status(404).json({
                err,
                message: 'Stock not found!',
            })
        }

        if( stock.ConsumedQuantity === undefined)
            stock.ConsumedQuantity = materialConsumed

        else
            stock.ConsumedQuantity += materialConsumed


        if( stock.WastageQuantity === undefined)
            stock.WastageQuantity = materialWasted

        else
            stock.WastageQuantity += materialWasted

        stock
            .save()
            .then(() => {

                return res.status(200).json({
                    success: true,
                    message: 'Material in inventory has been updated!',

                })
            })
            .catch(error => {

                return res.status(404).json({
                    error,
                    message: 'Material in inventory was not updated!',
                })
            })



    })

I want to be able to query my stock items based on two criteria, first the ClientId being equal to the clientId, a value I’m getting from the server request. Secondly I want the name of the stockItem to match a string. How do I go about doing this? Is there an AND operator I could use to perform ClientId : clientId and StockName : stockName in the same query? Please help! Thank you.

Leave a Reply

Your email address will not be published. Required fields are marked *