4
"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.

user1952811
  • 2,398
  • 6
  • 29
  • 49

1 Answers1

8

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});
David Weldon
  • 63,632
  • 11
  • 148
  • 146
  • It's not an object. It's an array of objects. I want to update a single object in that array. I have the index of that object in the array. What query should I use to update it? I do not want to get the whole array, add the object and then update the whole array. – Maaz Mar 21 '14 at 23:14
  • and I should be able to use a variable as an index for an array. Again, I am aware that the code I provided is likely wrong (pseudo-code). I should have been more clear, sorry about that. – Maaz Mar 21 '14 at 23:37
  • Sorry I think my phrasing was confusing - I was referring to the key in your pseudo-code: `vote_score[index]`. I'm not sure what `vote_score` is (maybe a typo). Anyway, the code I provided should update the `users_voted` array at the position specified by `index` with the value contained in `u_object`. If that isn't what you want, let me know. – David Weldon Mar 21 '14 at 23:42
  • This is working. Thanks! Also how can I remove the element from the array entirely, if I know the index of the element? Possibly using `$pull`? – user1952811 Mar 22 '14 at 07:07
  • Check out the answers to [this question](http://stackoverflow.com/questions/4588303/in-mongodb-how-do-you-remove-an-array-element-by-its-index) - it looks like you can use `$pull` but only by value (not by index). So: `Posts.update({_id: post_id}, {$pull: {'users_voted': u_object}});` – David Weldon Mar 22 '14 at 19:29
  • David that helped me in my case. Thank you very much! +1 – shish Dec 03 '15 at 09:06