0

My MongoDB database main document looks like this:

    {
        "_id": {
            "$oid": "568ad3db59b494d4284ac191"
        },
        "name": "Myclass",
        "items": [
          {
            "name": "Conductive Gel",
            "internal_id": "ID00067",
            "description": "ECG Conductive Gel",
            "short_description": "ECG Conduct. Gel",
            "providers": [
              {
                "name": "one",
                "address": ""
              },
              {
                "name": "two",
                "address": ""
              }
            ]

          },
          {

          }
        ]
   }

Ok the thing is that I am receiving an ajax put call that should update one of the items (the one that matches the _id).

My approach:

exports.updateItem = function(req, res, next) { 


              classes.findOne({_id: '568ad3db59b494d4284ac19d'}, function(e,myclass){
                    if(!e) {

                      myclass.items.forEach(function(item){
                        if (item._id == req.body._id) {

                            item = req.body;
                            myclass.save(function(err, doc){


                                if (err) return next(err);
                                return res.status(200).send('The item has been updated!');
                            });
                        }                              
                      });

                    } else {
                        res.status(500).send('Class not folund in BBDD!!');
                    }
                });
};

The thing is that when I do item = req.body; the req.body info is not mapped into the item mongoose object and the item in the database is not updated. I don't get any error either.

I have checked that req.body and item both have the exact same fields in the moment that I do the item = req.body; .

If I do item.name='whatever' , on the other hand, it works.

I've been fighting with this issue for 4 hours now without a solution...

I have also tried Mongoose's findOneAndUpdate() query without success..

Egidi
  • 1,736
  • 8
  • 43
  • 69

1 Answers1

1

If you assign item to a new value you are not actually changing the content of the array. item is just a reference to the element in the array.

What you probably want is to edit the content of the array by merging the two objects item and req.body.

require('extend'); // npm install extend
extend(item, req.body);

That will actually update the value in the array which will then be saved.

However, I recommend updating the subdocument using mongoose as explained here: Mongoose find/update subdocument

Community
  • 1
  • 1
4lejandrito
  • 182
  • 1
  • 6
  • Your solution worked! On the other hand, I tried the solution in your last recommendation and didn't work. – Egidi Jan 30 '16 at 17:14