将元素添加到meteor中的数组collections.update

时间:2021-10-01 15:57:05
    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.

基本上我已经_voted这是一个数组,我想在这个数组中添加一个新的ip。我目前处理这种方式的方法是获取旧的长度并使用旧的长度作为添加元素的新索引。

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.

澄清一下:我没有整个数组,我只想在Poll文档的数组中添加一个新元素。

2 个解决方案

#1


27  

Use the $push Mongo operator:

使用$ push Mongo运算符:

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

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

See the docs here.

请参阅此处的文档。

#2


2  

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

在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:

您甚至可以根据您的要求使用upsert而不是更新。像这样的东西:

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

#1


27  

Use the $push Mongo operator:

使用$ push Mongo运算符:

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

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

See the docs here.

请参阅此处的文档。

#2


2  

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

在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:

您甚至可以根据您的要求使用upsert而不是更新。像这样的东西:

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