3

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?

asked Dec 22, 2012 at 1:27

1 Answer 1

9

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...});
answered Dec 22, 2012 at 2:13
Sign up to request clarification or add additional context in comments.

3 Comments

For some reason I do not understand, if I say: var update = 'campaigns.' + position + ".campaign_id" and then $inc: {update: 1} does not work (where position is an integer). But works fine if I spell it out like above: $inc: {"campaigns.7.campaign_id": 1}. Do you know why?
Because you can't use a variable as a key name in a JavaScript immediate object. So you have to build up your update object programmatically. var update = {$inc: {}}; update.$inc['campaigns.' + position + ".campaign_id"] = 1;
ahh... interesting. Thanks!

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.