Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Mongoose model validation scope

Mongoose model validation scope

Problem

I'm starting my adventure with node, express and nodejs (I came from PHP env). While most of the stuff is quite straightforward, I want to maintain my models clean and I can't figure out how to separate Validation stuff, when it gets complex.

My Product model:

var mongoose = require('mongoose');
var schema = new mongoose.Schema({
     title: String,
     content: String,
     update_date: Date,
});

var model = mongoose.model ('Page', schema);

exports = module.exports = function (db) {   return db.model('Item');};

My questions:

  1. Is there any way (express extension) to handle validation scenarios/scopes (similar as in ror and yii)... Example validation scopes:
    • in "create" scope fields title,content should be required
    • in "update" scope field update_date should be required and validated with Date type
    • in "clear" scope fields content and update_date validated as empty
  2. Do you divide mongoose model (db abstration) and business model in express?
Problem courtesy of: spamec

Solution

Check out express-validator which will allow you to perform validation in your individual routes (controllers for the MVC inclined).

While the above works, mongoose gives you a lot of flexibility and already comes preloaded with validation mechanisms. Unless you REALLY need to, there is no point in rearchitecting this feature and doing so would require a lot of noise in your routes. I would consider homerolling with the native MongoDB driver and your own custom logic if you feel otherwise – its really not that hard to work with the native driver, but if the project is going to grow, mongoose gives you a lot of robust features that you won't want to handle yourself.

Though most tuts online show mongoose models in one big file, its relatively easy (and preferable) to split up your models into logical pieces. This is usually how I set up things:

models/
  User/
    index.js
    statics.js
    methods.js
    validators.js
    middleware.js
routes/
views/

Inside models/User/index.js, which can be required as require('./models/User'), we create our schema and add some glue code for our file splitting:

var mongoose = require('mongoose');

var userSchema = new mongoose.Schema({
   name: String,
   password: String,
   role: String
});

userSchema.statics = require('./statics');
userSchema.methods = require('./methods');

// This will go through each exports in the validators file and attach
// the exported function as a validator. You're validators file should
// name each validator after the field in which it intends to validate.
// See below for example validators file.
var validators = require('./validators');
Object.keys(validators).forEach(function (validator) {
  userSchema.path(validator).validate(validators[validator]);
  return;
});

// Do the following for each type of middleware you use in the model
var preSave = require('./middleware').preSave;
preSave.forEach(function (middleware) {
  userSchema.pre('save', middleware);
  return;
});

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

Then we can set up our validators.js file to look like:

exports['name'] = function () { /* validation code here */ };
exports['password'] = function () { /* validation code here */ };
exports['role'] = function () { /* validation code here */ };
//etc, etc, etc.    

You can take all of this a step further by rolling a plugin to provide this interface for you without all the boilerplate. I haven't gone down that road yet, but plugin development for mongoose is super simple: http://mongoosejs.com/docs/plugins.html

Keep in mind that express is not modeled after RoR or Yii. Sinatra, in ruby, is the closest to express outside the nodejs world. (I believe modeling after Sinatra is where TJ started and then the project morphed over the years to its current state).

Solution courtesy of: srquinn

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Mongoose model validation scope

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×