I am wondering if anyone can give an idea of ββthe best way to abstract the API built using Node.js + Restify + Mongoose. After exiting the MVC / PHP background, it is interesting to discover that for Node applications there is no string / specific structure.
At the moment, I have an app.js file that automatically downloads my routes.js file, all js model files, etc.
The confusion is primarily about how my routes should interact with data from Mongo. Below is a brief description of how my code is laid out.
app.js
var restify = require('restify') , mongoose = require('mongoose') , config = require('./config') , routes = require('./routes'); var server = restify.createServer({ name: config.name, version: config.version }); server.use(restify.acceptParser(server.acceptable)); server.use(restify.queryParser()); server.use(restify.bodyParser()); server.use(restify.jsonp()); mongoose.connect(config.mongo.uri, function(err) {
routes.js
module.exports.route = function(server, db) { var Users = require('./models/users.js'); server.get('/users', function (req, res, next) { res.send(Users.list(db, req, res)); return next(); }); server.get('/users/:user_id', function (req, res, next) { res.send(Users.get(db, req, res)); return next(); }); }
Models /users.js
// fake database var users = [ { name: 'Nick P', email: ' nick@domain.com ' }, { name: 'Zack S', email: ' zack@domain.com ' } ]; exports.list = function(db, req, res) { return users; }; exports.get = function(db, req, res) { return users[req.params.user_id]; };
As you can see, I am using a "fake database", which is a simple object. Where / how can I introduce a Mongoose layer to link to our database? I am mostly concerned about how I should use schemas and exports. Any code examples or direction would be awesome.