UNPKG

@brozeph/mongoose-middleware

Version:

Middleware for mongoose that makes filtering, sorting, pagination and projection chainable and simple to apply

91 lines (69 loc) 2.74 kB
"use strict"; var _interopRequireDefault = require("@babel/runtime-corejs2/helpers/interopRequireDefault"); var _Object$defineProperty = require("@babel/runtime-corejs2/core-js/object/define-property"); _Object$defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _parseInt2 = _interopRequireDefault(require("@babel/runtime-corejs2/core-js/parse-int")); var _promise = _interopRequireDefault(require("@babel/runtime-corejs2/core-js/promise")); var _default = function _default(mongoose) { var estimatedDocumentCount = true, maxDocs = -1, self = {}; function page(query, options) { return new _promise["default"](function (resolve, reject) { var countMethod = estimatedDocumentCount ? 'estimatedDocumentCount' : 'countDocuments'; return query.model[countMethod](query._conditions, function (err, total) { if (err) { return reject(err); } query.setOptions({ limit: options.count, skip: options.start }); return query.exec(function (err, results) { if (err) { return reject(err); } return resolve({ data: results || [], options: options, total: total }); }); }); }); } mongoose.Query.prototype.page = function (options, callback) { var defaults = { count: maxDocs, start: 0 }, query = this; options = options || defaults; // this might be getting a little long; options.start = options && options.start && (0, _parseInt2["default"])(options.start, 10) ? (0, _parseInt2["default"])(options.start, 10) : defaults.start; options.count = options && options.count && (0, _parseInt2["default"])(options.count, 10) ? (0, _parseInt2["default"])(options.count, 10) : defaults.count; if (maxDocs > 0 && (options.count > maxDocs || options.count === 0)) { options.count = maxDocs; } // if no callback is supplied, return a Promise if (typeof callback === 'undefined') { return page(query, options); } // execute and utilize the callback return page(query, options).then(function (result) { return callback(null, result); })["catch"](function (err) { return callback(err); }); }; self.initialize = function (options) { if (options) { // whether to use estimate or actual count estimatedDocumentCount = typeof options.estimatedDocumentCount !== 'undefined' ? options.estimatedDocumentCount : estimatedDocumentCount; // maximum size of page maxDocs = options.maxDocs || maxDocs; } }; return self; }; exports["default"] = _default; //# sourceMappingURL=page.js.map