tknew tknew - 1 year ago 70
Node.js Question

Chaining static constructor in Mongoose ? Like scope in Rails?

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.

Answer Source

[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

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('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) { ... });