Node.js Question

Not working with method "UPDATE" in API REST MEAN + Mongoose

exports.updateUsuarioByEmail = function (req, res) {
console.log('updateUsuarioByEmail');
console.log("PARAM ID" + req.params.email);
return Usuario.find({ email: req.params.email }, function(err, usuario) {
if(!usuario) {
res.statusCode = 404;
return res.send({ error: 'Not found' });
}
if (req.body.email != null) usuario.email = req.body.email;
if (req.body.password != null) usuario.password = req.body.password;
if (req.body.listaCardsSorting != null) usuario.listaCardsSorting = req.body.listaCardsSorting;

return usuario.save(function(err) {
if(!err) {
console.log('Updated usuario');
return res.send({ status: 'OK', usuario:usuario });
} else {
if(err.name == 'ValidationError') {
res.statusCode = 400;
res.send({ error: 'Validation error' });
} else {
res.statusCode = 500;
res.send({ error: 'Server error' });
}
console.log('Internal error(%d): %s',res.statusCode,err.message);
}
res.send(usuario);
});
});
};


The error after to execute is :
enter image description here

I believe that the error is the line
"return usuario.save(function(err)..."

Answer

find return an Array (list of documents) . you can't do save on an array object. Instead try findOne if your email field is unique.

findOne returns a single document, so you can save that.

Replace

Usuario.find({ email: req.params.email }, function(err, usuario)

with :

Usuario.findOne({ email: req.params.email }, function(err, usuario)