npm.io
0.2.0 • Published 11 years ago

genus

Licence
ISC
Version
0.2.0
Deps
5
Vulns
8
Weekly
0

genus

Genus is a simple library for creating Mongo models in Node. It's original inspiration is Sails` modeling, where models are defined in a folder (/models) with a simple JSON syntax. Genus takes the concept further by emphasizing extendability a great deal more than the original Sails modeling would allow.

Install

Somewhere in your server start

require('genus').init(previouslyEstablishedMongoConnection);

Usage

Register models

module.exports = genus.model('Person', {
	attributes: { // the attributes of the model
		name: {
			type: 'string', // tring, integer, or array
			required: true // is the field required?
		},
		email: {
		  type: 'string'
		},
		age: {
		  type: 'integer',
	  }
	},
	
	// by default every model has count, find, findOne, 
	// save, remove, validate, and clean methods
	
	// you can overwrite one of the default methods
	findOne: function (criteria) {
		return this.super.findOne.call(this, (criteria)).then(function() {
		  // Do something special
		});
	},
	
	// or add a new method
	findOneWithName: function (name) {
		return this.super.find.call(this, {name: name});
	}
});

Assuming I named that model file Person.js, I would now be able to access my model via

var Person = require('models/Person.js');
Person.findOneWithName('john')
  .then(function(personNamedJohn) {
  	personNamedJohn.name = 'Kelly';
  	return Person.save(req.session.userId, personNamedJohn);
  })
  .then(function(personFormerlyKnownAsJohn) {
	// etc
  });
Model default methods
  1. count(criteria) - mongo's count
  2. findOne(id or criteria) - mongo's findOne
  3. find(id or criteria) - mongo's find
  4. save(requestorId, itemToBeSaved) - mongo's update (with upsert true if the model is new)
  5. remove(criteria) - mongo's remove
  6. validate(itemToBeValidated) - validate that a given item fits the model defintion
  7. clean(itemToBeCleaned) - return a new item that contains only defined attributes