molleman
molleman

Reputation: 2946

How to increment a value within a subdocument of a document in mongodb with JavaScript

I would like to increment the quantity of a element within a subdocument of a document found in the database.

My find on the document works:

Cart.findOne({_id: '2JKD6eynaYmTGnbiZ',"items.productId": 'inkGTN7T89fqwEqTB' });

returning this:

{ _id: '2JKD6eynaYmTGnbiZ',

  items: 

   [ { _id: 'LYKPShnDDfYHS8zmx',

       productId: 'inkGTN7T89fqwEqTB',

       quantity: 1 } ],

  sessionId: 'jhizTjhiErYRNKhJW’ }

But I can't seem to increment the qty of an element within the items sub document with this update:

Cart.update({
    _id: '2JKD6eynaYmTGnbiZ’, "items.productId": ‘inkGTN7T89fqwEqTB'
}, {
    $set: {
        updatedAt: new Date()
    },
    $inc: {
        "items.quantity": 10
    }
});

I dont know if I am referencing it wrong, I have tried to use items.$.productId to refer to the element but won't even return the document on the find.

Upvotes: 1

Views: 294

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311855

You need to use the $ positional operator that represents the index of the matched items array element in your $inc:

Cart.update(
{
    _id: '2JKD6eynaYmTGnbiZ', "items.productId": 'inkGTN7T89fqwEqTB'
}, {
    $set: {
        updatedAt: new Date()
    },
    $inc: {
        "items.$.quantity": 10
    }
});

Upvotes: 1

Related Questions