genus
v0.2.0
Published
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
Downloads
8
Readme
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
- count(criteria) - mongo's count
- findOne(id or criteria) - mongo's findOne
- find(id or criteria) - mongo's find
- save(requestorId, itemToBeSaved) - mongo's update (with upsert true if the model is new)
- remove(criteria) - mongo's remove
- validate(itemToBeValidated) - validate that a given item fits the model defintion
- clean(itemToBeCleaned) - return a new item that contains only defined attributes