user1952811
user1952811

Reputation: 2468

Updating a specific element in an array with 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.

Upvotes: 4

Views: 1548

Answers (1)

David Weldon
David Weldon

Reputation: 64342

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});

Upvotes: 8

Related Questions