Mongoose Put method CastError

With the following put mongoose method, I get an error in postman if I do not fill all key/value pair!

app.put('/api/users/:user_id', function(req, res) {
    users.update({
        id_userLogin : req.body.id_userLogin,
        userName : req.body.userName,
        email : req.body.email,
        password : req.body.password,
        userNotes: req.body.userNotes
    }, function(err, user) {
        if (err)
            res.send(err);
        users.find(function(err, users) {
            if (err)
                res.send(err)
            res.json(users);
        });
    });
});

It works fine if I put all key/value pair but if it miss one pair, I get

"message": "Cast to string failed for value \"undefined\"",
"name": "CastError",
"type": "string"

if I add || "" for each params we can update the user with all empty params. In fact if a params is not updated we should keep the initial value

Any help would be appreciated



You should check all request parameters for plausibility and discard the request if it is malformed. For non-mandatory params (e.g., userNotes), you can set the param to an empty string if it is undefined:

app.put('/api/users/:user_id', function(req, res) {
    if (!req.id_userLogin || userName || password) {
        return res.send('Malformed request', 400);
    }
    users.update({
        id_userLogin : req.body.id_userLogin,
        userName : req.body.userName,
        email : req.body.email,
        password : req.body.password,
        userNotes: req.body.userNotes || ""
    }, function(err, user) {
        if (err)
            res.send(err);
        users.find(function(err, users) {
            if (err)
                res.send(err)
            res.json(users);
        });
    });
});

I move the code to for controller

exports.update = function(req, res, next) {
var id = req.params.id
User.findByIdAndUpdate(id, req.body, function(err, user) {
    if (err) {
        return next(err);
    } else {
        res.json(user);
    }
});

}

and for the route

app.route('/api/users/:id').put(users.update);

which fix the issue. With this method you can update one of the params