javascript - 更新数组内的对象 MongoDB Meteor

标签 javascript mongodb meteor mongodb-query

我正在尝试更新数组内的对象。这是我的结构:

"_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/

相关文章:

javascript - 根据MongoDB中另一个集合中的数据查询一个集合中的数据

javascript - 如何展示这个集合?

javascript - 使用 JQuery 将跨度添加到图像

javascript - 如何在动态 html 表 javascript 中选择选项值。未从 jsp 页面中的数据库获取更新的选项值

javascript - 如何判断 jQuery BlockUI 是否阻塞了页面

c# - 有没有办法获得唯一的计算机 ID?

node.js - 在 Mongoose 中更新/创建模型时,有什么理由将用户输入的数据列入白名单?

javascript - MongoDB $or 用于 $match 阶段内的两个字段

meteor - 如何在登录时拒绝 user.profile 的更新?

javascript - 开始使用 Meteor : Show/Hide Templates on click