Created
May 13, 2010 19:32
-
-
Save nw/400318 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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