【问题标题】:MongoDB updating array object within an arrayMongoDB 更新数组中的数组对象
【发布时间】:2018-12-30 12:54:18
【问题描述】:

模型结构:

{ _id: String, calc: [ { preset: String, datasets: [ { _id: String } ] } ] }

API 路由:

router.put('/:gameId/:preset/:datasetId', (req, res) => {
  Game.findOneAndUpdate({ _id: req.params.gameId, 'calc.preset': req.params.preset, 'calc.datasets._id': req.params.datasetId },
    { $set: { 'calc.$.datasets.$': req.body } })
    .then(() => res.status(200).json({ ...req.body, _id: req.params.datasetId }))
    .catch(err => res.status(500).json({ error: err }));
});

如果我要更新 calc 数组中的对象,那么我会:$set: { 'calc.$': newCalc },所以我遵循相同的方法来更新 datasets 数组中的对象,即对象内部,即 calc 数组中的对象,但是,$set: { 'calc.$.datasets.$': newDataset } 不起作用。

如何用_id: req.params.datasetId 更新一个对象,在datasets数组里面,也就是在calc数组的对象里面,preset:req.params.preset?

简而言之: { calc: [ { datasets: [ { set this object to a new dataset } ] } }

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    你可以使用$[]positional-all更新嵌套数组元素,$[]的mongo doc

    查询

    db.t14.update(
       {},
       { $set: { "calc.$[].datasets.$[elem].name": "updated" } },
       { arrayFilters: [  { "elem": "x1" } ], multi: true}
    )
    

    带有文档的样本集合

    > db.t14.findOne()
    {
            "_id" : 1,
            "calc" : [
                    {
                            "preset" : "abc",
                            "datasets" : [
                                    {
                                            "_id" : "x1",
                                            "name" : "n1"
                                    },
                                    {
                                            "_id" : "x2",
                                            "name" : "n2"
                                    }
                            ]
                    }
            ]
    }
    

    更新

    > db.t14.update({},{$set: { "calc.$[].datasets.$[elem].name": "newname" } },{ arrayFilters: [{ "elem.name": "n1" }], multi: true})
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
    

    发布更新

    > db.t14.findOne()
    {
            "_id" : 1,
            "calc" : [
                    {
                            "preset" : "abc",
                            "datasets" : [
                                    {
                                            "_id" : "x1",
                                            "name" : "newname"
                                    },
                                    {
                                            "_id" : "x2",
                                            "name" : "n2"
                                    }
                            ]
                    }
            ]
    }
    >
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-23
      • 2023-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-29
      相关资源
      最近更新 更多