我正在尝试更新数组内的对象。这是我的结构:
"_id": "ubtQP9EjmxhXS5z98",
"name": "My Data",
"desc": "What songs should I play at my wedding?",
"private": false,
"suggestions": [
{
"name": "Vote 1",
"link": "http://www.website.com/",
"votes": 0
},
{
"name": "Vote 2",
"votes": 0
}
],
"author": "tovd9Win3C3fntgyR",
"createdAt": "2016-01-10T08:36:37.014Z"
我想将“建议”中第一个对象的投票更新为 1。目前我有以下代码,但它不起作用。
Polls.update("ubtQP9EjmxhXS5z98", {
$inc: {suggestions.$.votes: 1},
});
最佳答案
如果您知道嵌入文档的数组索引,则可以使用 dot notation. 使用嵌入文档的位置来指定文档。
您不需要位置 $
此处更新运算符是因为您知道要更新的元素的位置。
The positional
$
operator identifies an element in an array to update without explicitly specifying the position of the element in the array.
要使用 $
运算符,数组字段必须作为查询文档的一部分出现。
Polls.update({"_id": "ubtQP9EjmxhXS5z98"}, {
"$inc": {"suggestions.1.votes": 1},
});
关于javascript - 更新数组内的对象 MongoDB Meteor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34703908/