0

currently I have a problem with updating existing JSON data using mongoose for nodejs. Here is my JSON data:

{
   "_id" : ObjectId("59fb4d91fa90e127d41ed7f5"),
    "heroes": [
        {
            "name": "antimage",
            "id": 1,
            "localized_name": "Anti-Mage",
            "_id" : ObjectId("59fc7230728a3e28203151a0")
        },
        {
            "name": "axe",
            "id": 2,
            "localized_name": "Axe",
            "_id" : ObjectId("59fc7230728a3e28203111a4")
        }
       ]
}

Here is my update request :

    // update a hero in the db
router.put('/heroes/:id', function (req, res, next) {
    //var id1 = req.params.id1;
    //var id  = req.params.id;
    Hero.update({ _id: '59fb4d91fa90e127d41ed7f5', 'heroes._id': req.params.id },
        {
            $push: {
                'heroes.$.name': req.body.name,
                'heroes.$.id': req.body.id,
                'heroes.$.localized_name': req.body.localized_name
            }
        }, { upsert: true }, function (err, docs) {
            res.json(docs);
            console.log(docs);
        });
})

it giving me this in the console:

    {
    "ok": 0,
    "n": 0,
    "nModified": 0
}

It makes me can't sleep, Btw thanks for your help.

  • You are copying from the wrong answer. You just want `Hero.update({ "_id" : ObjectId("59fb4d91fa90e127d41ed7f5") },{ "$push": { "heroes": { "name": req.body.name, "id": req.body.id, "localized_name": req.body.name } } }, function(err,doc) { ...`. I advise reading [MongoDB CRUD Operations](https://docs.mongodb.com/manual/crud/) in full after you have some sleep. – Neil Lunn Nov 03 '17 at 04:54
  • no bro, I want to update in heroes.JSON with _id = '59fb4d91fa90e127d41ed7f5' , then update the specifics heroes name by the _id when you feed it in params. So when I type it on the browser it will look like this http://localhost:4000/api/heroes/59fc7230728a3e28203151a0, and will update hero name by that _id = '59fc7230728a3e28203151a0' – sk8terdinz Nov 03 '17 at 10:02
  • Then you use [`$set`](https://docs.mongodb.com/manual/reference/operator/update/set/) and not `$push`. See the other link for examples, or simply replace `$push` with `$set` in the code you already have. – Neil Lunn Nov 03 '17 at 10:06
  • ok, You are the man... I remember I was try it before but no luck, but now when you tell me to change it works, thanks bro – sk8terdinz Nov 03 '17 at 10:11

0 Answers0