UNPKG

8.23 kBJavaScriptView Raw
1'use strict';
2
3/*!
4 * Module dependencies
5 */
6
7const checkEmbeddedDiscriminatorKeyProjection =
8 require('./helpers/discriminator/checkEmbeddedDiscriminatorKeyProjection');
9const get = require('./helpers/get');
10const isDefiningProjection = require('./helpers/projection/isDefiningProjection');
11const utils = require('./utils');
12
13/*!
14 * Prepare a set of path options for query population.
15 *
16 * @param {Query} query
17 * @param {Object} options
18 * @return {Array}
19 */
20
21exports.preparePopulationOptions = function preparePopulationOptions(query, options) {
22 const pop = utils.object.vals(query.options.populate);
23
24 // lean options should trickle through all queries
25 if (options.lean != null) {
26 pop.
27 filter(p => get(p, 'options.lean') == null).
28 forEach(makeLean(options.lean));
29 }
30
31 return pop;
32};
33
34/*!
35 * Prepare a set of path options for query population. This is the MongooseQuery
36 * version
37 *
38 * @param {Query} query
39 * @param {Object} options
40 * @return {Array}
41 */
42
43exports.preparePopulationOptionsMQ = function preparePopulationOptionsMQ(query, options) {
44 const pop = utils.object.vals(query._mongooseOptions.populate);
45
46 // lean options should trickle through all queries
47 if (options.lean != null) {
48 pop.
49 filter(p => get(p, 'options.lean') == null).
50 forEach(makeLean(options.lean));
51 }
52
53 const session = get(query, 'options.session', null);
54 if (session != null) {
55 pop.forEach(path => {
56 if (path.options == null) {
57 path.options = { session: session };
58 return;
59 }
60 if (!('session' in path.options)) {
61 path.options.session = session;
62 }
63 });
64 }
65
66 const projection = query._fieldsForExec();
67 pop.forEach(p => {
68 p._queryProjection = projection;
69 });
70
71 return pop;
72};
73
74
75/*!
76 * returns discriminator by discriminatorMapping.value
77 *
78 * @param {Model} model
79 * @param {string} value
80 */
81function getDiscriminatorByValue(model, value) {
82 let discriminator = null;
83 if (!model.discriminators) {
84 return discriminator;
85 }
86 for (const name in model.discriminators) {
87 const it = model.discriminators[name];
88 if (
89 it.schema &&
90 it.schema.discriminatorMapping &&
91 it.schema.discriminatorMapping.value == value
92 ) {
93 discriminator = it;
94 break;
95 }
96 }
97 return discriminator;
98}
99
100exports.getDiscriminatorByValue = getDiscriminatorByValue;
101
102/*!
103 * If the document is a mapped discriminator type, it returns a model instance for that type, otherwise,
104 * it returns an instance of the given model.
105 *
106 * @param {Model} model
107 * @param {Object} doc
108 * @param {Object} fields
109 *
110 * @return {Model}
111 */
112exports.createModel = function createModel(model, doc, fields, userProvidedFields) {
113 model.hooks.execPreSync('createModel', doc);
114 const discriminatorMapping = model.schema ?
115 model.schema.discriminatorMapping :
116 null;
117
118 const key = discriminatorMapping && discriminatorMapping.isRoot ?
119 discriminatorMapping.key :
120 null;
121
122 const value = doc[key];
123 if (key && value && model.discriminators) {
124 const discriminator = model.discriminators[value] || getDiscriminatorByValue(model, value);
125 if (discriminator) {
126 const _fields = utils.clone(userProvidedFields);
127 exports.applyPaths(_fields, discriminator.schema);
128 return new discriminator(undefined, _fields, true);
129 }
130 }
131
132 return new model(undefined, fields, {
133 skipId: true,
134 isNew: false,
135 willInit: true
136 });
137};
138
139/*!
140 * ignore
141 */
142
143exports.applyPaths = function applyPaths(fields, schema) {
144 // determine if query is selecting or excluding fields
145 let exclude;
146 let keys;
147 let ki;
148 let field;
149
150 if (fields) {
151 keys = Object.keys(fields);
152 ki = keys.length;
153
154 while (ki--) {
155 if (keys[ki][0] === '+') {
156 continue;
157 }
158 field = fields[keys[ki]];
159 // Skip `$meta` and `$slice`
160 if (!isDefiningProjection(field)) {
161 continue;
162 }
163 exclude = field === 0;
164 break;
165 }
166 }
167
168 // if selecting, apply default schematype select:true fields
169 // if excluding, apply schematype select:false fields
170
171 const selected = [];
172 const excluded = [];
173 const stack = [];
174
175 const analyzePath = function(path, type) {
176 const plusPath = '+' + path;
177 const hasPlusPath = fields && plusPath in fields;
178 if (hasPlusPath) {
179 // forced inclusion
180 delete fields[plusPath];
181 }
182
183 if (typeof type.selected !== 'boolean') return;
184
185 if (hasPlusPath) {
186 // forced inclusion
187 delete fields[plusPath];
188
189 // if there are other fields being included, add this one
190 // if no other included fields, leave this out (implied inclusion)
191 if (exclude === false && keys.length > 1 && !~keys.indexOf(path)) {
192 fields[path] = 1;
193 }
194
195 return;
196 }
197
198 // check for parent exclusions
199 const pieces = path.split('.');
200 const root = pieces[0];
201 if (~excluded.indexOf(root)) {
202 return;
203 }
204
205 // Special case: if user has included a parent path of a discriminator key,
206 // don't explicitly project in the discriminator key because that will
207 // project out everything else under the parent path
208 if (!exclude && get(type, 'options.$skipDiscriminatorCheck', false)) {
209 let cur = '';
210 for (let i = 0; i < pieces.length; ++i) {
211 cur += (cur.length === 0 ? '' : '.') + pieces[i];
212 const projection = get(fields, cur, false);
213 if (projection && typeof projection !== 'object') {
214 return;
215 }
216 }
217 }
218
219 (type.selected ? selected : excluded).push(path);
220 return path;
221 };
222
223 analyzeSchema(schema);
224
225 switch (exclude) {
226 case true:
227 for (let i = 0; i < excluded.length; ++i) {
228 fields[excluded[i]] = 0;
229 }
230 break;
231 case false:
232 if (schema &&
233 schema.paths['_id'] &&
234 schema.paths['_id'].options &&
235 schema.paths['_id'].options.select === false) {
236 fields._id = 0;
237 }
238 for (let i = 0; i < selected.length; ++i) {
239 fields[selected[i]] = 1;
240 }
241 break;
242 case undefined:
243 if (fields == null) {
244 break;
245 }
246 // Any leftover plus paths must in the schema, so delete them (gh-7017)
247 for (const key of Object.keys(fields || {})) {
248 if (key.startsWith('+')) {
249 delete fields[key];
250 }
251 }
252
253 // user didn't specify fields, implies returning all fields.
254 // only need to apply excluded fields and delete any plus paths
255 for (let i = 0; i < excluded.length; ++i) {
256 fields[excluded[i]] = 0;
257 }
258 break;
259 }
260
261 function analyzeSchema(schema, prefix) {
262 prefix || (prefix = '');
263
264 // avoid recursion
265 if (stack.indexOf(schema) !== -1) {
266 return [];
267 }
268 stack.push(schema);
269
270 const addedPaths = [];
271 schema.eachPath(function(path, type) {
272 if (prefix) path = prefix + '.' + path;
273
274 const addedPath = analyzePath(path, type);
275 if (addedPath != null) {
276 addedPaths.push(addedPath);
277 }
278
279 // nested schemas
280 if (type.schema) {
281 const _addedPaths = analyzeSchema(type.schema, path);
282
283 // Special case: if discriminator key is the only field that would
284 // be projected in, remove it.
285 if (exclude === false) {
286 checkEmbeddedDiscriminatorKeyProjection(fields, path, type.schema,
287 selected, _addedPaths);
288 }
289 }
290 });
291
292 stack.pop();
293 return addedPaths;
294 }
295};
296
297/*!
298 * Set each path query option to lean
299 *
300 * @param {Object} option
301 */
302
303function makeLean(val) {
304 return function(option) {
305 option.options || (option.options = {});
306 option.options.lean = val;
307 };
308}
309
310/*!
311 * Handle the `WriteOpResult` from the server
312 */
313
314exports.handleDeleteWriteOpResult = function handleDeleteWriteOpResult(callback) {
315 return function _handleDeleteWriteOpResult(error, res) {
316 if (error) {
317 return callback(error);
318 }
319 const mongooseResult = Object.assign({}, res.result);
320 if (get(res, 'result.n', null) != null) {
321 mongooseResult.deletedCount = res.result.n;
322 }
323 if (res.deletedCount != null) {
324 mongooseResult.deletedCount = res.deletedCount;
325 }
326 return callback(null, mongooseResult);
327 };
328};