forked from mongoosejs/mongoose-lean-getters
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
78 lines (68 loc) · 1.78 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
'use strict';
const mpath = require('mpath');
module.exports = function mongooseLeanGetters(schema) {
const fn = applyGettersMiddleware(schema);
// Use `pre('find')` so this also works with `cursor()`
// and `eachAsync()`, because those do not call `post('find')`
schema.pre('find', function() {
if (typeof this.map === 'function') {
this.map((res) => {
fn.call(this, res);
return res;
});
} else {
this.options.transform = (res) => {
fn.call(this, res);
return res;
};
}
});
schema.post('findOne', fn);
schema.post('findOneAndUpdate', fn);
};
function applyGettersMiddleware(schema) {
return function(res) {
applyGetters.call(this, schema, res);
};
}
function applyGetters(schema, res) {
if (res == null) {
return;
}
if (this._mongooseOptions.lean && this._mongooseOptions.lean.getters !== false) {
if (Array.isArray(res)) {
const len = res.length;
for (let i = 0; i < len; ++i) {
applyGettersToDoc(schema, res[i]);
}
} else {
applyGettersToDoc(schema, res);
}
for (let i = 0; i < schema.childSchemas.length; ++i) {
const _path = schema.childSchemas[i].model.path;
const _schema = schema.childSchemas[i].schema;
const _doc = mpath.get(_path, res);
if (_doc == null) {
continue;
}
applyGetters.call(this, _schema, _doc);
}
return res;
} else {
return res;
}
}
function applyGettersToDoc(schema, doc) {
if (doc == null) {
return;
}
if (Array.isArray(doc)) {
for (let i = 0; i < doc.length; ++i) {
applyGettersToDoc(schema, doc[i]);
}
return;
}
schema.eachPath((path, schematype) => {
mpath.set(path, schematype.applyGetters(mpath.get(path, doc), doc, true), doc);
});
}