如何在MongoDB中更新嵌套JSON数组的特定值?

时间:2018-04-23 17:55:46

标签: json node.js mongodb mongoose

我正在尝试使用Node.js中的mongoose更新特定字段,这是我的JSON数据:

{
    "farms": [
        {
            "extension": {
                "extension": 30,
                "measure": "Hectares"
            },
            "animals": [],
            "outs": [],
            "plans": [],
            "_id": "5ade19a531db34383b3e0bed",
            "name": "Farm 2",
            "updatedAt": "2018-04-23T17:36:37.680Z",
            "createdAt": "2018-04-23T17:36:37.680Z"
        },
        {
            "extension": {
                "extension": 30,
                "measure": "Hectares"
            },
            "animals": [],
            "outs": [],
            "plans": [],
            "_id": "5ade19c831db34383b3e0bef",
            "name": "Farm 3",
            "updatedAt": "2018-04-23T17:37:12.307Z",
            "createdAt": "2018-04-23T17:37:12.307Z"
        }
    ],
    "_id": "5ade19a5c47476697ec0d155",
    "username": "john99",
    "__v": 0,
    "createdAt": "2018-04-23T17:36:37.680Z",
    "updatedAt": "2018-04-23T17:37:12.307Z"
}

我想更新“Farm 2”的名称字段。这是我用来更新的代码:

exports.update = (req, res) => { // fix me
  User.update (
    { username: 'john99',
      farms: {
        $elemMatch: { _id: "5ade19a531db34383b3e0bed"  } } 
    },
    { $set: {
       farms: { name: "Farm 99" } } } 
  )
    .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 User with ID " + req.params.idFarm
      });
    });
};

这是上面代码的输出:

{
    "farms": [
        {
            "animals": [],
            "outs": [],
            "plans": [],
            "_id": "5ade1b9c7213483b1b38b60f",
            "name": "Farm 99"
        }
    ],
    "_id": "5ade19a5c47476697ec0d155",
    "username": "john99",
    "__v": 0,
    "createdAt": "2018-04-23T17:36:37.680Z",
    "updatedAt": "2018-04-23T17:45:00.822Z"
}

正如您所看到的,当我尝试更新名称字段时,该用户的所有服务器场都将被删除,只留下一个服务器场但数据不完整(没有扩展字段,createdAt,updatedAt), 如何解决?

1 个答案:

答案 0 :(得分:0)

它应该可以解决你的问题!

   User.update({'_id': ObjectId('5ade19a5c47476697ec0d155'), 
                'farms._id' : '5ade19a531db34383b3e0bed'}, 
                {$set: {'famrs.$.name': 'farm 99'}}
               ).then(farm =>{....});