Models in node.js and data validation

 Development, node.js  Comments Off on Models in node.js and data validation
Nov 292011

So I have been learning about node.js and I have to say that so far I am finding myself warming to it.

I wanted to write a little bit about how I’ve enjoyed using models in a node.js app using the Express web framework.

I am using mongodb for this app and so I am using the mongoose data layer. Mongoose is described as a object modeling tool.

You define a model as follows:

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

/event model/

var Event = new Schema({
title : {type: String, index: true}
, content : {type: String}
, startdate : Date
, enddate : Date
, creator : Schema.ObjectId
, longlat : {lon:Number,lat:Number}
, county : {type:String, index:true}


Since writing this piece I have found out that there is a better way of achieving the same result. You can add validators to mongoosejs Schemas as follows:

if(\/\/[a-z0-9\-\.]+\.[a-z][a-z][a-z\.]*/gi) !== -1){
return true;
return false;
}, "link error");

The path is the path to the field in the schema and the second arg is the type of error which will be thrown.

What I have really liked is the “middleware” options. So you can define methods which will be called at a certain point in the execution; for example pre save.
Here is an example:


var errors = [];
console.log("I was called first before save");
if(this.title.length < 20) errors[errors.length] = {field:"title",message:"title invalid"}; if(errors.length > 0){
var error = new Error("Invalid Input");
error.errors = errors;


So in the above code next is the next function to be called in the chain which ends with the call back defined after save was called on the model

/some controller method

saveEvent : function(req,res){
var event = new Event();
event.title = req.body.title;,suc){
//control is returned here
if(err){ //do something with errors}

You can define more than one function in your model to be called pre some event in this case the next will refer to the next peice of middleware.

For more info on mongoose you can see here Middle ware in mongoose

© 2012 Craig Brookes Suffusion theme by Sayontan Sinha