swag-mvc
v0.1.2
Published
connecting your models and routes in node.js
Downloads
5
Readme
swag-mvc
connecting your models and routes in node.js
Creating
var mvc = require('mvc')( app )
Pass inexpress.createServer()
Models
mvc.initModels( models, dir, setupFunction, args )
sets up models indir
defined in the array of stringsmodels
.setupFunction
has two arguments, one is the capitalized name of the model and the other is the return value of the model file indir/ModelName
to hook it into your database of choice.args
are arguments passed into the model file.
Routes
mvc.initRoutes( routes, dir, args )
sets up the routes indir
, defined with an array of stringsroutes
, passing inapp
, corresponding model if applicable, followed by additionalargs
.
Example
app.js
mvc = require('mvc')( app );
db = mongoose.connect( url );
mvc.initModels( [ 'User' ], __dirname + '/models/', function ( name, schema ) {
db.model( name, schema );
return db.model( name );
}, {
mongoose: mongoose
});
mvc.initRoutes( [ 'users', 'pages', 'sesions' ], __dirname + '/controllers/', {
auth: function ( req, res, next ) {
req.isAuthenticated() ? next() : res.redirect( '/login' );
});
});
ROOT/controllers/users.js
// Passing in arguments app, the model, and arguments object passed in
// during initRoutes
module.exports = function ( app, User, args ) {
app.get( '/users', function ( req, res, next ) {
User.find( {}, ( err, users ) {
if ( !err ) { res.render( 'users/idnex', { users: users } }
});
});
app.get( '/register', function ( req, res, next ) {
res.render( '/users/new' );
});
};
ROOT/models/User.js
module.exports = function ( args ) {
mongoose = args.mongoose;
ObjectId = mongoose.SchemaTypes.ObjectId;
UserSchema = new mongooose.Schema({});
// this is the schema passed into the
// setupFunction in initModels
return UserSchema;
};