Is there a way to chain static constructor in mongoose ?
In Rails its the way to chain named_scopes
I have a special query to retrieve some data from mongo, but some time I have to apply a limit or to count them.
[Update] This feature has been removed.
Mongoose has named scope capabilities, but there is an unresolved issue that may indicate they're not working correctly; check the feature out and see if it works for you. (I will be doing this as well, when I get a chance, as it's a really nice feature to have!)
The following example code is taken from the named scope test at https://github.com/LearnBoost/mongoose/blob/master/test/namedscope.test.js.
var UserNSSchema = new Schema({
age: Number
, gender: String
, lastLogin: Date
});
UserNSSchema.namedScope('olderThan', function (age) {
return this.where('age').gt(age);
});
UserNSSchema.namedScope('youngerThan', function (age) {
return this.where('age').lt(age);
});
UserNSSchema.namedScope('twenties').olderThan(19).youngerThan(30);
UserNSSchema.namedScope('male').where('gender', 'male');
UserNSSchema.namedScope('female').where('gender', 'female');
UserNSSchema.namedScope('active', function () {
return this.where('lastLogin').gte(+new Date - _24hours)
});
mongoose.model('UserNS', UserNSSchema);
UserNS.olderThan(20).find(function (err, found) { ... });
UserNS.olderThan(40).active.male.find(function (err, found) { ... });
Just extend the Mongoose Query object and you will be able to chain your methods. Like so
mongoose.Query.prototype.customPopulate = function(populate) { var query = this; var model = this.model; if(populate != null) { return query.populate(populate); } else{ return query; } }