在更新mongodb上设置动态键

时间:2018-06-30 20:11:35

标签: javascript mongodb mongoose

我有mongoDB companies集合

c00:
    {
        _id: c00,
        name: 'acme',
        results: [
            0: { _id: 'a10', name: 'foo', visible: true },
            1: { _id: 'a11', name: 'bar', visible: false }
        ],
    },
c01:
    {
        _id: c01,
        name: 'apra'
        results: [
            0: { _id: 'b10', name: 'foo', visible: false },
            1: { _id: 'b11', name: 'bar', visible: true },
            2: { _id: 'b12', name: 'qux', visible: true },
        ]
    }
}

我需要修改的查询

company.c01.results,其resultId ==='b11'`

{ _id: 'b11', name: 'bar', visible: false }

我尝试过

  CompanyModel
    .update(
      { [`${companyId}.results`]: resultsId },
      {
        $set: { ['results.$.visible']: false },
      }
    )

但这没用。
任何帮助将不胜感激

2 个答案:

答案 0 :(得分:1)

尝试

CompanyModel.update(
    { "company.c01.sets._id": "b11" }, 
    { "$set": { "company.$.c01.visible": false } }
)

答案 1 :(得分:1)

您还需要在ba r 1 0x11223344时放置动态密钥

$set