Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add element to array collections.update in meteor

    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.

like image 881
user1952811 Avatar asked Feb 20 '14 12:02

user1952811


People also ask

How to add an element to array in mongodb?

If the value is an array, $push appends the whole array as a single element. To add each element of the value separately, use the $each modifier with $push . For an example, see Append a Value to Arrays in Multiple Documents. For a list of modifiers available for $push , see Modifiers.

How do you update an element in an array?

To update all the elements of an array, call the forEach() method on the array, passing it a function. The function gets called for each element in the array and allows us to update the array's values.

Can you add data to array?

When you want to add an element to the end of your array, use push(). If you need to add an element to the beginning of your array, try unshift(). And you can add arrays together using concat().

What is Meteor collection?

Collections are Meteor's way of storing persistent data. The special thing about collections in Meteor is that they can be accessed from both the server and the client, making it easy to write view logic without having to write a lot of server code.


2 Answers

Use the $push Mongo operator:

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

See the docs here.

like image 125
Tobias Avatar answered Oct 18 '22 02:10

Tobias


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}});
like image 33
Ashwini Shelke Avatar answered Oct 18 '22 02:10

Ashwini Shelke