Skip to content

Instantly share code, notes, and snippets.

@nw
Created May 13, 2010 19:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nw/400318 to your computer and use it in GitHub Desktop.
Save nw/400318 to your computer and use it in GitHub Desktop.
Model.define('User',{
collection : 'test_user', // (optional) if not present uses the model name instead.
// defines your data structure
types: {
_id : Object, // if not defined, Mongoose automatically defines for you.
username: String,
first : String,
last : String,
bio: {
age: Number
}
},
indexes : [
'username',
'bio.age',
[['first'],['last']] // compound key indexes
],
static : {}, // adds methods onto the Model.
methods : {}, // adds methods to Model instances.
setters: { // custom setters
first: function(v){
return v.toUpperCase();
}
},
getters: { // custom getters
username: function(v){
return v.toUpperCase();
},
legalDrinkingAge : function(){
return (this.bio.age >= 21) ? true : false;
},
first_last : function(){ // custom getter that merges two getters together.
return this.first + ' ' + this.last;
}
}
});
Mongoose.load('./models/');
User = Mongoose.get('User');
user = new User({username : 'test', first : 'me', last : 'why', bio : { age : 100 }}); // create a new document.
user.save(); //save
user.first_last // returns 'ME why'
user.legalDrinkingAge // true
// you can set new properties that aren't defined on the model
user.new_property = 'test';
user.save();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment