Rusticman Rusticman -4 years ago 90
Javascript Question

incrementing sub-document key using mongoose

I would really appreciate some help regarding the below noted. The problem is I want to increment the

keys
such as 'eagle', 'bear', etc by one. My data model looks like this:

{
"_id" : ObjectId("57e134097a578b11eruogf0a2cb"),
"email" : "test3@example.com",
"password" : "$2a$10$KU8vmE./gewfuh3445ryh7hDC426k0Ttd2",
"userName" : "person",
"votedFor" : [],
"polls" : [
{
"items" : {
"eagle" : 3,
"bear" : 5,
"lion" : 3,
"giraffe" : 0,
"elephant" : 0,
"monkey" : 0,
"gorilla" : 0,
"dog" : 0,
"cat" : 0
},
"_id" : ObjectId("57e39435erthytvf4c16149b3fcd"),
"pollTitle" : "if you could be any animal, which one would you be?"
}
]
}


Here are the attempts I've made without success:

User.update({"polls._id":ObjectId("57e39435erthytvf4c16149b3fcd"),
"polls.items.bear":{$exists:true}}, {$inc:{"polls.$.items.bear":1}})


The above actually works with robomongo but curiously doesn't within my app. It actually creates a new key:
"__v" :
.

The latest attempt looks something like this which is more of a desperate attempt at grabbing the whole document and manipulating it in a cumbersome way:

var pollItem = "bear", mongoose = require('mongoose'),
pollID = "57e39435erthytvf4c16149b3fcd",
id = mongoose.Types.ObjectId(pollID);

User.findOne({"polls._id" :id},function(err,user){
if(err){
return err;
}


user.polls.forEach(function(poll){


if(poll._id.valueOf() == pollID){

var value = poll.items[pollItem];
poll.items[pollItem] = value + 1;
return poll;
}
return poll;
})

user.save(function(err){
if(err){

return (err);
}
console.log('successfully saved');
})

});


Unfortunately, it doesn't appear to save the changes to the document.If anyone could point me in the right direction, I'd be most grateful.

Answer Source

I figured it out, it seems you need to reference every level of the document in the query object in order to update the correct field in the update object. I've tried to find the documentation for this but I can't, so it's a bit of an assumption, unless some sagacious SO user could confirm this as the reason. Here's what I did:

User.update({"_id":ObjectId("57e134097a578b11f060a2cb"),
"polls._id":ObjectId("57e39435c4af4c16149b3fcd"),
"polls.items.dog":{$exists:true}},
{$inc:{"polls.$.items.dog":1}})

Hope this helps someone.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download