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.
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.
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.
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().
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.
Use the $push
Mongo operator:
Polls.update({ _id: id },{ $push: { already_voted: ip }})
See the docs here.
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}});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With