Last active
August 29, 2015 13:56
-
-
Save kharmabum/8929189 to your computer and use it in GitHub Desktop.
Mongoose list/load static functions.
This file contains hidden or 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
/** | |
* Load | |
* | |
* @param {Object} options | |
* @param {Function} cb | |
* @api private | |
*/ | |
schema.statics.load = function (options, cb) { | |
var criteria = options.criteria || {} | |
var populate = options.populate || [] | |
var select = options.select || '' | |
this.findOne(criteria) | |
.select(options.select) | |
.populate(options.populate) | |
.exec(cb) | |
} | |
/** | |
* List | |
* | |
* The use of having `list` method is, you can create your own statics | |
* | |
* Example: | |
* | |
* UserSchema.static({ | |
* deleted: function (cb) { | |
* this.list({ | |
* criteria: { deleted: true }, | |
* sort: { name: 'desc' } | |
* limit: 20, | |
* populate: [{ | |
* path: 'company', select: 'name', match: { deleted: false } | |
* }], | |
* select: 'name email' | |
* }, cb) | |
* } | |
* }) | |
* | |
* @param {Object} options | |
* @param {Function} cb | |
* @api private | |
*/ | |
schema.statics.list = function (options, cb) { | |
var criteria = options.criteria || {} | |
var sort = options.sort || { createdAt: -1 } | |
var limit = options.limit === 0 ? 0 : (options.limit || 10) | |
var page = options.page || 0 | |
var populate = options.populate || [] | |
var select = options.select || '' | |
this.find(criteria) | |
.select(options.select) | |
.populate(options.populate) | |
.sort(sort) | |
.limit(limit) | |
.skip(limit * page) | |
.exec(cb) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment