Increment a {key: value} within an array of objects with MongoDB Mongoose driver

increment, mongodb, mongoose

Solution

You've got the right idea, but your `upsert` option isn't formatted correctly.

Try this:

camps.findOneAndUpdate(
    {name: "John"}, 
    {$inc: {"campaigns.7.campaign_id": 1}}, 
    {upsert: true},
    function(err, camp) {...etc...});

Problem

I have a document that looks similar to this: ``` { 'user_id':'{1231mjnD-32JIjn-3213}', 'name':'John', 'campaigns': [ { 'campaign_id':3221, 'start_date':'12-01-2012', 'worker_id': '00000' }, { 'campaign_id':3222, 'start_date':'13-01-2012', 'worker_id': '00000' }, ... etc ... ] } ``` Say I want to increment the `campaign_id` of element 7 in the `campaigns` array. Using the dot with the mongoose driver, I thought I could do this: `camps.findOneAndUpdate({name: "John"}, {$inc: {"campaigns.7.campaign_id": 1}}, upsert: true, function(err, camp) {...etc...});` This doesn't increment the `campaign_id`. Any suggestions on incrementing this?

Original source