david raja
david raja

Reputation: 87

Node js not saving method PUT

I am trying to update object values inside of array. I have done the method and search the element in the array that I want, and returns me 200. But after when I do another request the value return to the original (is not saving).

First of all this is the schema:

    { 
         "_id" : "1",
         "username" : "a",
         "elements" : [{"_id": "22", "name":"bb"}, {"_id":"33", "name": "cc"}]   
    }

and this is my method

update = function(req, res) {
        User.findById(req.params.id, function (err, user) {
        if (!user) {
            res.send(404, 'User not found');
        }
        else{
            var array = user.elements;
            for (var i = 0; i < array.length; i++) { 
                if (array[i]._id == "22") { 
                  result = array[i];
                  if (req.body.name != null) result.name = req.body.name;
                  result.save(function(err) {
                      if(!err) {
                          console.log('Updated');
                      } 
                      else {
                          console.log('ERROR: ' + err);
                      }
                      res.send(result);
                  });
                  break;
                } 
            }
        }
        });
    }

I don't know what I am doing wrong. I mean I simplified everything but I think that the problem is in the method.

Upvotes: 0

Views: 144

Answers (1)

El houcine bougarfaoui
El houcine bougarfaoui

Reputation: 37383

You have to save the user object and result just like this :

  update = function(req, res) {
            User.findById(req.params.id, function (err, user) {
            if (!user) {
                res.send(404, 'User not found');
            }
            else{
                var array = user.elements;
                for (var i = 0; i < array.length; i++) { 
                    if (array[i]._id == "22") { 
                      result = array[i];
                      if (req.body.name != null) result.name = req.body.name;

                      break;
                    } 
                }
                 user.save(function(err) {
                          if(!err) {
                              console.log('Updated');
                          } 
                          else {
                              console.log('ERROR: ' + err);
                          }
                          res.send(user);
                      });
            }
            });

        }

Upvotes: 1

Related Questions