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

Problem

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

Here's how I save it:

app.post('/create', function(req, res){
    var firstUser = new models.User(req.body);
    firstUser.save();
});

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

Solution

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.

app.post('/create', function(req, res){
    var firstUser = new models.User(req.body);
    firstUser.save(function (err) {
        if (err) {
            res.send(500, { error: 'Saving first user failed!' });
        } else {
            res.send({ success: 'Saved!' }); 
        }
    })
});
Solution courtesy of: Frank

Discussion

There is currently no discussion for this recipe.

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