4

I'm curious if anyone could provide some insight on the best way to abstract an API built with Node.js + Restify + Mongoose. After coming from an MVC / PHP background, it's interesting to find that there's not string/defined structure for Node applications.

As of now, I have my app.js file that auto loads my routes.js file, all model js files, etc.

The confusion is primarily in how my routes are supposed to interact with data from Mongo. Here is a basic rundown on how my code is layed out.

app.js:

/**
 * Require Dependencies
 */
var restify    = require('restify')
    , mongoose = require('mongoose')
    , config   = require('./config')
    , routes   = require('./routes');

/**
 * Create Server & Define Settings
 */
var server = restify.createServer({
    name: config.name,
    version: config.version
});

/**
 * Common Handlers
 */
server.use(restify.acceptParser(server.acceptable));
server.use(restify.queryParser());
server.use(restify.bodyParser());
server.use(restify.jsonp());

/**
 * Connect to Mongo Database
 */
 mongoose.connect(config.mongo.uri, function(err) {

    // assign connection to var so we can pass it down the chain
    var db = mongoose.connection;

    // handle connection error
    db.on('error', console.error.bind(console, 'connection error:'));

    // handle connection success
    db.once('open', function callback () {

        /**
         * Start Routing API Calls
         */
        routes.route(server, db);

    });

});

/**
 * Start Server & Bind to Port
 */
server.listen(config.port, function () {
    console.log('%s v%s listening on port %s in %s mode.', server.name, server.version,          config.port, config.env);
});

routes.js:

module.exports.route = function(server, db) {

    var Users = require('./models/users.js');

    /**
     * Users
     */

    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: '[email protected]'
    },
    {
        name: 'Zack S',
        email: '[email protected]'
    }
];

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'm using a "fake database" that is a simple object. Where / how could I introduce a Mongoose layer to communicate with our database? I'm mostly concerned with how I should use schemas and exports. Any code examples, or direction would be awesome.

3
  • Just make Users.list use mongoose to access the database instead of just returning the fake database. Maybe I don't understand the question.
    – Chad
    Jan 8, 2013 at 18:12
  • @Chad I figured it would be as simple as that. However, I'm also new to Mongoose and it looks like they require schema definitions. Wasn't positive on where I should put those [Mongoose Schemas] mongoosejs.com/docs/guide.html Jan 8, 2013 at 19:42
  • Wherever you want, I usually have them as part of the model.
    – Chad
    Jan 8, 2013 at 19:45

1 Answer 1

7

Here a simple example of what I usually do with Express, it's kind of the same thing with Restify. You can manage your Mongoose schemas in the same way but in your Restify routes.

app.js :

var express = require('express');     
var app = express();

app.configure(function () {
    app.use(express.logger('dev'));
    app.use(express.bodyParser());
});

// connection to mongoDB
var mongoose = require('mongoose');
mongoose.connect('mongodb:mongoURI');    

var user = require('./routes/users');

app.get('/users/list', user.list);

app.listen(3000);

models/user.js :

var mongoose = require('mongoose')
   ,Schema = mongoose.Schema
   ,ObjectId = Schema.ObjectId;

var userSchema = new Schema({
    id: ObjectId,
    name: {type: String, default: ''},
    email: {type: String, default: ''}
});

module.exports = mongoose.model('User', userSchema);

routes/users.js :

var User = require('../models/user.js');

exports.list = function(req, res) {
    User.find(function(err, users) {
        res.send(users);
    });
};
5
  • So your models only contain schema definitions? And your routes handle all of the database interaction? I guess I'm a bit confused when it comes to models / routes. In PHP controllers and routes can be used interchangeably (they call upon your models) and your models are what handle any data / manipulation. Jan 8, 2013 at 21:12
  • It depend of what kind of manipulation I need to do, I consider my routes like controllers in PHP. When I do some heavy data manipulation I prefer doing it outside of the route in a service lets say something like service/user.js and use that service inside my route. All that logic can be in the model but I prefer keeping it clean with only my schema and use it like an entity. I Guess it's my preference. Jan 8, 2013 at 21:28
  • 1
    There are two widely used patterns when working with data - ActiveRecord and Repository. In the first one, all operations on the data are methods on the persistent object itself. In the second, all opearions are members of a repository object and you pass the persisted object as an argument. @NickParsons Maybe this is why you are confused. The model itself may reside in a separate file, but what you do with it (delete, create, update) may be in the controller (or route).
    – Slavo
    Jan 9, 2013 at 10:11
  • @JpBond You should also add a var mongoose = require('mongoose') in app.js.
    – Slavo
    Jan 9, 2013 at 10:13
  • That helps clear things up a bit @Slavo. Do you have any particular preference towards the usage of routes over controllers? That's another convention that I'm not quite sure of yet. They seem to be used interchangeably. Jan 9, 2013 at 14:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.