mongodb - meteor /MongoDB : Update an array item in a collection by index

标签 mongodb meteor minimongo

这是我的收藏结构的概述:

{
  profile: {
    first_name: 'Plop',
    surname: 'Plopette',
    ...
  },
  medical_history: {
    significant_illnesses: [
      'Asthma',
      'Diabetes'
    ],
    ...
  }
}

如何访问和更新 medical_history.significant_illnesses 数组中的一项?

我所拥有的是惨败:

Patients.update(Session.get("current_patient"), {
    $push: {
        "medical_history.significant_surgeries.surgeryIndex": $(event.target).val().trim()
    }
});

注意surgeryIndex 是动态的,因此我无法对任何内容进行硬编码。

上面的更新代码会产生此错误:

Exception while simulating the effect of invoking '/patients/update'

errorClass {
    error: 409,
    reason: "MinimongoError: can't append to array using string field name [surgeryIndex]",
    details: undefined, message: "MinimongoError: can't append to array using string field name [surgeryIndex] [409]",
    errorType: "Meteor.Error"}

最佳答案

最好的方法是取出数组,修改它并使用 $set 查询更新回来。

如果你真的想按照自己想要的方式去做,你需要 $pull数组中的值,然后您必须使用 $position 将其推送到特定索引运算符。

但是 $position 运算符是在 2.6 版本中引入的。如果您使用的版本比该版本更旧,据我所知,除了我的第一个建议之外,您没有其他选择。

关于mongodb - meteor /MongoDB : Update an array item in a collection by index,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38862847/

相关文章:

mongodb - 蒙戈错误: Incorrect arguments

javascript - 类型错误 : Cannot use 'in' operator to search for '_id' in [{}]

mongodb服务没有启动

javascript - 自定义忘记密码电子邮件.Meteorjs

Meteor minimongo动态光标

MongoDB:计算重复字段、mapReduce 与 python 循环

node.js - 如何通过对象名称获取全局对象

javascript - 采集字段中的 meteor 计算值

javascript - MongoDB:更新嵌套数组元素或如果不存在则将其插入