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.

1 Answer 1

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});
Sign up to request clarification or add additional context in comments.

6 Comments

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.
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.
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.
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?
Check out the answers to this question - 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}});
|

Your Answer

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.