-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
43 lines (37 loc) · 1.4 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
module.exports = function selectVirtuals(schema) {
function preFind(next) {
if (!this.selected() || !this._mongooseOptions.lean) {
return next();
}
var selection = this._fields;
var virtualFields = [];
Object.keys(selection).forEach(function (path) {
if (schema.pathType(path) === 'virtual') {
virtualFields.push(path);
delete selection[path];
}
});
if (virtualFields.length > 0) {
if (this._mongooseOptions.lean === true) {
this._mongooseOptions.lean = {};
}
this._mongooseOptions.lean.virtuals = virtualFields;
// At this point there was at least one virtual field mentioned in the selection. If
// there are no more fields left in the selection, it means only virtual fields
// were selected and we shouldn't return any real fields. We need to explicitly set
// only the `_id` field to come back since leaving the selection object blank would
// return all real fields.
if (Object.keys(selection).length === 0) {
selection['_id'] = 1;
}
} else if (Object.keys(selection).length > 0) {
// There are real fields specified, but no virtual keys specified
// In this case, don't return any virtuals
this._mongooseOptions.lean = true;
}
next();
}
schema.pre('find', preFind);
schema.pre('findOne', preFind);
schema.pre('findOneAndUpdate', preFind);
};