-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
79 lines (69 loc) · 1.76 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
79
const mpath = require('mpath')
module.exports = function mongooseLeanMethods(schema) {
const fn = attachMethodsMiddleware(schema)
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('find', fn)
schema.post('findOne', fn)
schema.post('findOneAndUpdate', fn)
schema.post('findOneAndRemove', fn)
schema.post('findOneAndDelete', fn)
}
function attachMethodsMiddleware(schema) {
return function (res) {
attachMethods.call(this, schema, res)
}
}
function attachMethods(schema, res) {
if (res == null) {
return
}
if (this._mongooseOptions.lean && this._mongooseOptions.lean.methods) {
const methods = {}
for (const key in schema.methods) {
if (key === 'initializeTimestamps') continue
methods[key] = schema.methods[key]
}
if (Array.isArray(res)) {
const len = res.length
for (let i = 0; i < len; ++i) {
res[i] = attachMethodsToDoc(res[i], methods)
}
} else {
res = attachMethodsToDoc(res, methods)
}
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
}
attachMethods.call(this, _schema, _doc)
}
return res
} else {
return res
}
}
function attachMethodsToDoc(doc, methods) {
if (!doc) return
if (Object.keys(methods).length === 0) {
return doc
}
for (const key in methods) {
doc[key] = methods[key]
}
return doc
}