0

I'm trying to update a specific field using mongoose in Node.js, this is my JSON data:

{
    "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"
}

I want to update the name field of the "Farm 2". This is the code that I'm using to update:

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
      });
    });
};

This is the output of the code above:

{
    "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"
}

As you can see, when I try to update the name field, all the farms of that user are deleted and only leave a farm but with incomplete data (without the extension field, createdAt, updatedAt), How to fix it?

alex22596
  • 13
  • 4

1 Answers1

0

It should resolve your problem!

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