thoughts/node_modules/mongoose/lib/namedscope.js
node_modules/mongoose/lib/namedscope.jsRaw
1var Query = require('./query');
2function NamedScope () {}
3
4NamedScope.prototype.query;
5
6NamedScope.prototype.where = function () {
7 var q = this.query || (this.query = new Query());
8 q.where.apply(q, arguments);
9 return q;
10};
11
12/**
13 * Decorate
14 *
15 * @param {NamedScope} target
16 * @param {Object} getters
17 * @api private
18 */
19
20NamedScope.prototype.decorate = function (target, getters) {
21 var name = this.name
22 , block = this.block
23 , query = this.query;
24 if (block) {
25 if (block.length === 0) {
26 Object.defineProperty(target, name, {
27 get: getters.block0(block)
28 });
29 } else {
30 target[name] = getters.blockN(block);
31 }
32 } else {
33 Object.defineProperty(target, name, {
34 get: getters.basic(query)
35 });
36 }
37};
38
39NamedScope.prototype.compile = function (model) {
40 var allScopes = this.scopesByName
41 , scope;
42 for (var k in allScopes) {
43 scope = allScopes[k];
44 scope.decorate(model, {
45 block0: function (block) {
46 return function () {
47 var cquery = this._cumulativeQuery || (this._cumulativeQuery = new Query().bind(this));
48 block.call(cquery);
49 return this;
50 };
51 },
52 blockN: function (block) {
53 return function () {
54 var cquery = this._cumulativeQuery || (this._cumulativeQuery = new Query().bind(this));
55 block.apply(cquery, arguments);
56 return this;
57 };
58 },
59 basic: function (query) {
60 return function () {
61 var cquery = this._cumulativeQuery || (this._cumulativeQuery = new Query().bind(this));
62 cquery.find(query);
63 return this;
64 };
65 }
66 });
67 }
68};
69
70module.exports = NamedScope;