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.

4
  • 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 in full after you have some sleep. Commented Nov 3, 2017 at 4: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 localhost:4000/api/heroes/59fc7230728a3e28203151a0, and will update hero name by that _id = '59fc7230728a3e28203151a0' Commented Nov 3, 2017 at 10:02
  • Then you use $set and not $push. See the other link for examples, or simply replace $push with $set in the code you already have. Commented Nov 3, 2017 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 Commented Nov 3, 2017 at 10:11

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.