Static methods

Schemas are flexible enough so that you can easily add your own custom static methods to them, which will then become available to all of your models that are defined by that Schema. Static methods are great for adding helper utilities and functions that you know you're going to want to use with most of your models. Let's take our simple age query from earlier and refactor it so that it's a static method and a little more flexible:

var Account = new Schema({
username: { type: String },
date_created: { type: Date, default: Date.now },
visits: { type: Number, default: 0 },
active: { type: Boolean, default: false },
age: { type: Number, required: true, min: 13, max: 120 }
});

Account.statics.findByAgeRange = function(min, max, callback) {
this.find({ age: { $gt: min, $lte: max } }, callback);
};

var AccountModel = mongoose.model('Account', Account);

AccountModel.findByAgeRange(18, 30, function(err, accounts) {
console.log(accounts.length); // => 2
});

Static methods are pretty easy to implement and will make your models much more powerful once you start taking full advantage of them!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.204.0