Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Incrementing number in an object of mongoose array

I am trying to increment the number in MongoDB using mongoose. But I start failing right at the query stage. When I // @ts-ignore it flows silently with no error but the value doesn’t update.

The error it throws out is: Type 'number' is not assignable to type 'undefined'

My Schema:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const CartSchema: Schema<Document<ICart>> = new Schema({
    clientID: { type: String, required: true },
    sourceID: { type: String, required: true },
    items: {
        id: { type: Types.ObjectId },
        amount: { type: Number },
        grindHow: { type: String, trim: true },
        grind: Boolean,
        package: { type: String, trim: true },
        price: { type: Number },
        productID: { type: String },
        productName: { type: String },
        totalProduct: { type: Number },
    },
    source: { type: String, required: true },
}, { collection: "carts", timestamps: true });

CartSchema.virtual('cartTotal').get(function() {
    // @ts-ignore
    const self: any = this;
    
    if(self.items && self.items.length) {
        return self.items.reduce((acc: BigNumber, current: any) => acc.plus(current.totalProduct), new BigNumber(0))
    } else {
        return 0
    }
})

The way I am trying to implement that is:

const item = await CartModel.findOneAndUpdate({ sourceID: clientID, 'items.id': itemID }, { $inc: { 'items.$.amount': 1 }}).lean({ virtuals: true })

I also tried with updateOne. I thought maybe it’s more flexible.

That's where it highlights it

>Solution :

items is not an array, it is an object. You should access it with items.amount and NOT with items.$.amount. Change your query like this:

const item = await CartModel.findOneAndUpdate({ sourceID: clientID, 'items.id': itemID }, { $inc: { 'items.amount': 1 }}).lean({ virtuals: true })
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading