-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathindex.js
62 lines (57 loc) · 1.25 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
'use strict';
module.exports = function mongooseLeanId(schema) {
schema.post('find', attachId);
schema.post('findOne', attachId);
schema.post('findOneAndUpdate', attachId);
schema.post('findOneAndReplace', attachId);
schema.post('findOneAndDelete', attachId);
};
function attachId(res) {
if (res == null) {
return
}
function replaceId(res) {
if (Array.isArray(res)) {
res.forEach(v => {
if (isObjectId(v)) {
return;
}
if (v._id) {
v.id = v._id.toString();
}
Object.keys(v).map(k => {
if (Array.isArray(v[k])) {
replaceId(v[k]);
}
});
});
} else {
if (isObjectId(res)) {
return res;
}
if (res._id) {
res.id = res._id.toString();
}
Object.keys(res).map(k => {
if (Array.isArray(res[k])) {
replaceId(res[k]);
}
});
}
}
if (this._mongooseOptions.lean) {
replaceId(res);
}
}
function isObjectId(v) {
if (v == null) {
return false;
}
const proto = Object.getPrototypeOf(v);
if (proto == null ||
proto.constructor == null ||
proto.constructor.name !== 'ObjectId') {
return false;
}
return v._bsontype === 'ObjectId';
}