12
    Polls.update({_id: id}, {$set : {already_voted[length]: ip});

Now this obviously doesn't work. I can't simply put a variable "length" in there.

Basically I have already_voted which is an array and I want to add a new ip to this array. The way I handle this currently is by getting the old length and using the old length as the new index to add the element.

I am wondering how I should go about doing this as my current setup does not work.

To clarify : I don't have the whole array, I just want to add a new element into the array in the Poll document.

3
  • Do you mean you "have" the whole array and you want to add the member that is not present in the stored document array? It's not really clear what you are saying. Commented Feb 20, 2014 at 12:14
  • I don't have the whole array. I just have a value that I want to add into an array called already_voted in my Polls documents. Commented Feb 20, 2014 at 12:20
  • That makes it clearer and now you have an answer. Commented Feb 20, 2014 at 12:32

2 Answers 2

30

Use the $push Mongo operator:

Polls.update({ _id: id },{ $push: { already_voted: ip }})

See the docs here.

Sign up to request clarification or add additional context in comments.

1 Comment

Better yet. Combine that with $set in case it's a new document, adding upsert
2

It is quite easy to add element to array in collection in meteor:

collection.update({_id: "unique id"},{$push:{already_voted: ip}});

You can even user upsert instead of update as per you requirement. something like this:

collection.upsert({_id: "unique id"},{$push:{already_voted: ip}});

1 Comment

Welcome to Stack Overflow. Your answer appears to be very similar to the existing and accepted answer, plus its comments. A new answer to an old question should add new information if it is to be useful. Please read the How to Answer pages to see how to write a good answer.

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.