Chris
Chris

Reputation: 3174

Design Pattern for working with IF/ELSE in Node JS / Express / Mongoose

I've quite a big application built, and constantly seeing this appearing across the application when working with mongoose:

Version.create({ version: req.body.version }, function (error, version) {
    if (error) {
        res.send(501, error)
    }
    else {
        res.send(201, version);
    }
});

The If/Else statement to send errors or content.

Is there a better way of doing this?

Upvotes: 0

Views: 258

Answers (1)

Ben Fortune
Ben Fortune

Reputation: 32127

The common way to do it with JavaScript is to return early.

Version.create({ version: req.body.version }, function (error, version) {
    if (error) {
        return res.send(501, error)
    }
    res.send(201, version);
});

Upvotes: 3

Related Questions