Reputation: 4229
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.
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.
};
// 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);
}
});
});
};
Upvotes: 1
Views: 156
Reputation: 39522
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.
Upvotes: 1