Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating a specific element in an array with MongoDB / Meteor

Tags:

mongodb

meteor

"users_voted" : [ 
    {
        "user_id" : "AQG8ECLdBRJ4jwPMG",
        "score" : "down"
    }
]

Wondering how I would go about updating the users_voted field which is an array objects. I need to have a specific object updated. I know the index at which this object is located, I simply need to figure out how I can update that object in a MongoDB / Meteor collection.

This is some pseudo-code that I have to better explain what I mean.

Posts.update({_id: post_id}, {$set: {vote_score[index]: u_object}});

So in this query I know index and post_id as well as u_object is the object that I am trying to put into the array in place of whatever object that was there at that index. If someone could help let me know how I should go about this, it would be great.

like image 249
user1952811 Avatar asked Feb 13 '23 10:02

user1952811


1 Answers

You can't use variables as keys in an object literal. Give this a try:

var obj = {};
obj["users_voted." + index] = u_object;
Posts.update({_id: post_id}, {$set: obj});
like image 165
David Weldon Avatar answered Feb 16 '23 21:02

David Weldon