How do I return an error message to the client after failed Mongoose validation in Express


I have a very basic POST route that creates a new user out of the given data.

Here's how I save it:'/create', function(req, res){
    var firstUser = new models.User(req.body);;

My Mongoose User schema has a few validation options, which work. If I pass the wrong data, validation fails and the user isn't created.

But there's a problem: Mongoose's save() function is asynchronous, so how do I let the client now the validation failed?

The post function will be done by then.

Problem courtesy of: skerit


You should have a look at Mongoose documentation. Because save method is asynchronous it takes a callback as parameter. This is where you should check for errors.'/create', function(req, res){
    var firstUser = new models.User(req.body); (err) {
        if (err) {
            res.send(500, { error: 'Saving first user failed!' });
        } else {
            res.send({ success: 'Saved!' }); 
Solution courtesy of: Frank


There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.