如何使用Node.js中的Mongoose更新嵌套json数组中的可选字段?

时间:2018-04-29 23:52:21

标签: node.js mongodb mongoose

我正在尝试更新属于用户的服务器场的可选字段。例如,如果用户只想更改"农场1"到"农场99",JSON将像这样发送:

{
    "name": "Farm 99"
}

这是有两个农场的用户的示例:

     }
         "farms": [
            {
                "extension": {
                    "extension": 22,
                    "measure": "Hectares"
                },
                "animals": [],
                "outs": [],
                "plans": [],
                "_id": "5ae64b9f9564b42d31e5bb99",
                "name": "Farm 1",
                "createdAt": "2018-04-29T22:47:59.514Z",
                "updatedAt": "2018-04-29T22:47:59.514Z"
            },
            {
                "extension": {
                    "extension": 50,
                    "measure": "Hectares"
                },
                "animals": [],
                "outs": [],
                "plans": [],
                "_id": "5ae64ceeda4eb82e50502901",
                "name": "Farm 2",
                "updatedAt": "2018-04-29T22:53:34.467Z",
                "createdAt": "2018-04-29T22:53:34.467Z"
            }
        ],
        "_id": "5ae64b9f9564b42d31e5bb98",
        "name": "John",
        "lastName": "Doe",
        "username": "john99",
        "password": "123",
        "createdAt": "2018-04-29T22:47:59.514Z",
        "updatedAt": "2018-04-29T22:53:34.467Z",
        "__v": 0
    }

这是我正在使用的代码:

exports.update = (req, res) => { // fix me
  User.update (
    { username: req.params.username, 'farms._id' : req.params.idFarm },
    { $set: {
      farms: req.body
    } }
  )
    .then(farm => {
      if (!farm) {
        return res.status(404).send({
          message: "Farm not found with ID  " + req.params.idFarm
        });
      }
      res.send(farm);

    })
    .catch(err => {
      if (err.kind === "ObjectId") {
        return res.status(404).send({
          message: "Farm not Found with ID " + req.params.idFarm
        });
      }
      return res.status(500).send({
        message: "Error Updating Farm with ID " + req.params.idFarm
      });
    });
};

这就是结果:

"farms": [
            {
                "animals": [],
                "outs": [],
                "plans": [],
                "_id": "5ae659c55dacc836066102f3",
                "name": "Farm 99"
            }
        ],

正如您所看到的,当您尝试更新时,所有服务器场都将被删除,只有您尝试更新但具有不完整字段的服务器场将被删除。

1 个答案:

答案 0 :(得分:0)

因为您正在更新整个数组,所以只有更新的对象才会出现在数组中。您需要将$set运算符与$ positional运算符一起使用。

User.update (
{ username: req.params.username, 'farms._id' : req.params.idFarm },
{ $set: { "farms.$.name": req.body.name } } )

这应该只替换数组中受影响的对象,并仅更新name属性。

如果您想要替换整个对象,请尝试以下方法:

User.update (
{ username: req.params.username, 'farms._id' : req.params.idFarm },
{ $set: { "farms.$": req.body } } )

希望有所帮助。

干杯