Question

I'm building some web-services with node.js / Express 3 / Mongoose / MongoDB. I generally see two ways people move code for routes from server.js to an external files and I'd like to know what's the main difference, and if one is better than the other? I've outlined the two techniques below. I tend to use method 2 but I find that the require('./routes/cats')(app, CatModel); with no var = before it just doesn't look right.

  1. By Function. Routes are build in-line in server.js but the logic is moved to external files.

Some people seem to do it this way:

// server.js

app.get('/cats', cats.findAll);

// routes/cats.js

exports.findAll = function(req, res) {
    // Lookup all the cats in MongoDB / CatModel.
};
  1. By App. App is passed in and the routes are built on top of it.

// in server.js

require('./routes/cats')(app, CatModel);

// in routes/cats.js

module.exports = function(app, CatModel) {
    app.get('/cats', function (req, res) {
        CatModel.find({}, function (err, docs) {
            if (err || !docs) {
                res.json(kStatusInternalServerError, {error: err});
                console.log(err);
            } else {
                res.json(kStatusOk, docs);
            }
        });
    });
};
Was it helpful?

Solution

The default way is the first one - and that's why most of us use it. I prefer to have all of my routes nicely lined up in app.js, with all of whatever's actually happening elsewhere. I haven't seen the second way in production, and I don't see the advantage of tangling routing in with logic.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top