Monday, 22 May 2017

Mongoose - Error on .save() on PUT request

I have a User model where I put the password field as required. The problem is that when I try to update a User without sending a password, an error is raised because it says the password is required.

How do I set the password to required when creating, but not on updating? Extending this, how do I create an endpoint that can receive from 1 to 4 attributes on the request?

PUT endpoint

exports.putUsuario = function(req, res) {
    Usuario.findById(req.user._id, function(err, usuario) {
        if (err)
            res.send(err);

        if (usuario){
        // Update the existing beer quantity
        usuario.password = req.body.password;
        usuario.nome = req.body.nome;
        usuario.sexo = req.body.sexo;
        usuario.idade = req.body.idade;

        // Save the beer and check for errors
        usuario.save(function(err) {
            if (err)
                res.send(err);

            res.json(usuario);
        });
      }
      else {
        res.json(usuario);
      }
    });
};

Error returned to Postman

{
  "errors": {
    "password": {
      "message": "Path `password` is required.",
      "name": "ValidatorError",
      "properties": {
        "type": "required",
        "message": "Path `{PATH}` is required.",
        "path": "password"
      },
      "kind": "required",
      "path": "password"
    }
  },
  "message": "Usuario validation failed",
  "name": "ValidationError"
}



via Minoru

No comments:

Post a Comment