1 | ;
|
2 |
|
3 | /*!
|
4 | * Module dependencies.
|
5 | */
|
6 |
|
7 | const CastError = require('./error/cast');
|
8 | const DocumentNotFoundError = require('./error/notFound');
|
9 | const Kareem = require('kareem');
|
10 | const MongooseError = require('./error/mongooseError');
|
11 | const ObjectParameterError = require('./error/objectParameter');
|
12 | const QueryCursor = require('./cursor/QueryCursor');
|
13 | const ReadPreference = require('./driver').get().ReadPreference;
|
14 | const applyGlobalMaxTimeMS = require('./helpers/query/applyGlobalMaxTimeMS');
|
15 | const applyWriteConcern = require('./helpers/schema/applyWriteConcern');
|
16 | const cast = require('./cast');
|
17 | const castArrayFilters = require('./helpers/update/castArrayFilters');
|
18 | const castUpdate = require('./helpers/query/castUpdate');
|
19 | const completeMany = require('./helpers/query/completeMany');
|
20 | const get = require('./helpers/get');
|
21 | const promiseOrCallback = require('./helpers/promiseOrCallback');
|
22 | const getDiscriminatorByValue = require('./helpers/discriminator/getDiscriminatorByValue');
|
23 | const hasDollarKeys = require('./helpers/query/hasDollarKeys');
|
24 | const helpers = require('./queryhelpers');
|
25 | const isInclusive = require('./helpers/projection/isInclusive');
|
26 | const mquery = require('mquery');
|
27 | const parseProjection = require('./helpers/projection/parseProjection');
|
28 | const selectPopulatedFields = require('./helpers/query/selectPopulatedFields');
|
29 | const setDefaultsOnInsert = require('./helpers/setDefaultsOnInsert');
|
30 | const slice = require('sliced');
|
31 | const updateValidators = require('./helpers/updateValidators');
|
32 | const util = require('util');
|
33 | const utils = require('./utils');
|
34 | const wrapThunk = require('./helpers/query/wrapThunk');
|
35 |
|
36 | /**
|
37 | * Query constructor used for building queries. You do not need
|
38 | * to instantiate a `Query` directly. Instead use Model functions like
|
39 | * [`Model.find()`](/docs/api.html#find_find).
|
40 | *
|
41 | * ####Example:
|
42 | *
|
43 | * const query = MyModel.find(); // `query` is an instance of `Query`
|
44 | * query.setOptions({ lean : true });
|
45 | * query.collection(MyModel.collection);
|
46 | * query.where('age').gte(21).exec(callback);
|
47 | *
|
48 | * // You can instantiate a query directly. There is no need to do
|
49 | * // this unless you're an advanced user with a very good reason to.
|
50 | * const query = new mongoose.Query();
|
51 | *
|
52 | * @param {Object} [options]
|
53 | * @param {Object} [model]
|
54 | * @param {Object} [conditions]
|
55 | * @param {Object} [collection] Mongoose collection
|
56 | * @api public
|
57 | */
|
58 |
|
59 | function Query(conditions, options, model, collection) {
|
60 | // this stuff is for dealing with custom queries created by #toConstructor
|
61 | if (!this._mongooseOptions) {
|
62 | this._mongooseOptions = {};
|
63 | }
|
64 | options = options || {};
|
65 |
|
66 | this._transforms = [];
|
67 | this._hooks = new Kareem();
|
68 | this._executionCount = 0;
|
69 |
|
70 | // this is the case where we have a CustomQuery, we need to check if we got
|
71 | // options passed in, and if we did, merge them in
|
72 | const keys = Object.keys(options);
|
73 | for (let i = 0; i < keys.length; ++i) {
|
74 | const k = keys[i];
|
75 | this._mongooseOptions[k] = options[k];
|
76 | }
|
77 |
|
78 | if (collection) {
|
79 | this.mongooseCollection = collection;
|
80 | }
|
81 |
|
82 | if (model) {
|
83 | this.model = model;
|
84 | this.schema = model.schema;
|
85 | }
|
86 |
|
87 | // this is needed because map reduce returns a model that can be queried, but
|
88 | // all of the queries on said model should be lean
|
89 | if (this.model && this.model._mapreduce) {
|
90 | this.lean();
|
91 | }
|
92 |
|
93 | // inherit mquery
|
94 | mquery.call(this, this.mongooseCollection, options);
|
95 |
|
96 | if (conditions) {
|
97 | this.find(conditions);
|
98 | }
|
99 |
|
100 | this.options = this.options || {};
|
101 |
|
102 | // For gh-6880. mquery still needs to support `fields` by default for old
|
103 | // versions of MongoDB
|
104 | this.$useProjection = true;
|
105 |
|
106 | const collation = get(this, 'schema.options.collation', null);
|
107 | if (collation != null) {
|
108 | this.options.collation = collation;
|
109 | }
|
110 | }
|
111 |
|
112 | /*!
|
113 | * inherit mquery
|
114 | */
|
115 |
|
116 | Query.prototype = new mquery;
|
117 | Query.prototype.constructor = Query;
|
118 | Query.base = mquery.prototype;
|
119 |
|
120 | /**
|
121 | * Flag to opt out of using `$geoWithin`.
|
122 | *
|
123 | * mongoose.Query.use$geoWithin = false;
|
124 | *
|
125 | * MongoDB 2.4 deprecated the use of `$within`, replacing it with `$geoWithin`. Mongoose uses `$geoWithin` by default (which is 100% backward compatible with `$within`). If you are running an older version of MongoDB, set this flag to `false` so your `within()` queries continue to work.
|
126 | *
|
127 | * @see http://docs.mongodb.org/manual/reference/operator/geoWithin/
|
128 | * @default true
|
129 | * @property use$geoWithin
|
130 | * @memberOf Query
|
131 | * @receiver Query
|
132 | * @api public
|
133 | */
|
134 |
|
135 | Query.use$geoWithin = mquery.use$geoWithin;
|
136 |
|
137 | /**
|
138 | * Converts this query to a customized, reusable query constructor with all arguments and options retained.
|
139 | *
|
140 | * ####Example
|
141 | *
|
142 | * // Create a query for adventure movies and read from the primary
|
143 | * // node in the replica-set unless it is down, in which case we'll
|
144 | * // read from a secondary node.
|
145 | * var query = Movie.find({ tags: 'adventure' }).read('primaryPreferred');
|
146 | *
|
147 | * // create a custom Query constructor based off these settings
|
148 | * var Adventure = query.toConstructor();
|
149 | *
|
150 | * // Adventure is now a subclass of mongoose.Query and works the same way but with the
|
151 | * // default query parameters and options set.
|
152 | * Adventure().exec(callback)
|
153 | *
|
154 | * // further narrow down our query results while still using the previous settings
|
155 | * Adventure().where({ name: /^Life/ }).exec(callback);
|
156 | *
|
157 | * // since Adventure is a stand-alone constructor we can also add our own
|
158 | * // helper methods and getters without impacting global queries
|
159 | * Adventure.prototype.startsWith = function (prefix) {
|
160 | * this.where({ name: new RegExp('^' + prefix) })
|
161 | * return this;
|
162 | * }
|
163 | * Object.defineProperty(Adventure.prototype, 'highlyRated', {
|
164 | * get: function () {
|
165 | * this.where({ rating: { $gt: 4.5 }});
|
166 | * return this;
|
167 | * }
|
168 | * })
|
169 | * Adventure().highlyRated.startsWith('Life').exec(callback)
|
170 | *
|
171 | * @return {Query} subclass-of-Query
|
172 | * @api public
|
173 | */
|
174 |
|
175 | Query.prototype.toConstructor = function toConstructor() {
|
176 | const model = this.model;
|
177 | const coll = this.mongooseCollection;
|
178 |
|
179 | const CustomQuery = function(criteria, options) {
|
180 | if (!(this instanceof CustomQuery)) {
|
181 | return new CustomQuery(criteria, options);
|
182 | }
|
183 | this._mongooseOptions = utils.clone(p._mongooseOptions);
|
184 | Query.call(this, criteria, options || null, model, coll);
|
185 | };
|
186 |
|
187 | util.inherits(CustomQuery, model.Query);
|
188 |
|
189 | // set inherited defaults
|
190 | const p = CustomQuery.prototype;
|
191 |
|
192 | p.options = {};
|
193 |
|
194 | // Need to handle `sort()` separately because entries-style `sort()` syntax
|
195 | // `sort([['prop1', 1]])` confuses mquery into losing the outer nested array.
|
196 | // See gh-8159
|
197 | const options = Object.assign({}, this.options);
|
198 | if (options.sort != null) {
|
199 | p.sort(options.sort);
|
200 | delete options.sort;
|
201 | }
|
202 | p.setOptions(options);
|
203 |
|
204 | p.op = this.op;
|
205 | p._conditions = utils.clone(this._conditions);
|
206 | p._fields = utils.clone(this._fields);
|
207 | p._update = utils.clone(this._update, {
|
208 | flattenDecimals: false
|
209 | });
|
210 | p._path = this._path;
|
211 | p._distinct = this._distinct;
|
212 | p._collection = this._collection;
|
213 | p._mongooseOptions = this._mongooseOptions;
|
214 |
|
215 | return CustomQuery;
|
216 | };
|
217 |
|
218 | /**
|
219 | * Specifies a javascript function or expression to pass to MongoDBs query system.
|
220 | *
|
221 | * ####Example
|
222 | *
|
223 | * query.$where('this.comments.length === 10 || this.name.length === 5')
|
224 | *
|
225 | * // or
|
226 | *
|
227 | * query.$where(function () {
|
228 | * return this.comments.length === 10 || this.name.length === 5;
|
229 | * })
|
230 | *
|
231 | * ####NOTE:
|
232 | *
|
233 | * Only use `$where` when you have a condition that cannot be met using other MongoDB operators like `$lt`.
|
234 | * **Be sure to read about all of [its caveats](http://docs.mongodb.org/manual/reference/operator/where/) before using.**
|
235 | *
|
236 | * @see $where http://docs.mongodb.org/manual/reference/operator/where/
|
237 | * @method $where
|
238 | * @param {String|Function} js javascript string or function
|
239 | * @return {Query} this
|
240 | * @memberOf Query
|
241 | * @instance
|
242 | * @method $where
|
243 | * @api public
|
244 | */
|
245 |
|
246 | /**
|
247 | * Specifies a `path` for use with chaining.
|
248 | *
|
249 | * ####Example
|
250 | *
|
251 | * // instead of writing:
|
252 | * User.find({age: {$gte: 21, $lte: 65}}, callback);
|
253 | *
|
254 | * // we can instead write:
|
255 | * User.where('age').gte(21).lte(65);
|
256 | *
|
257 | * // passing query conditions is permitted
|
258 | * User.find().where({ name: 'vonderful' })
|
259 | *
|
260 | * // chaining
|
261 | * User
|
262 | * .where('age').gte(21).lte(65)
|
263 | * .where('name', /^vonderful/i)
|
264 | * .where('friends').slice(10)
|
265 | * .exec(callback)
|
266 | *
|
267 | * @method where
|
268 | * @memberOf Query
|
269 | * @instance
|
270 | * @param {String|Object} [path]
|
271 | * @param {any} [val]
|
272 | * @return {Query} this
|
273 | * @api public
|
274 | */
|
275 |
|
276 | Query.prototype.slice = function() {
|
277 | if (arguments.length === 0) {
|
278 | return this;
|
279 | }
|
280 |
|
281 | this._validate('slice');
|
282 |
|
283 | let path;
|
284 | let val;
|
285 |
|
286 | if (arguments.length === 1) {
|
287 | const arg = arguments[0];
|
288 | if (typeof arg === 'object' && !Array.isArray(arg)) {
|
289 | const keys = Object.keys(arg);
|
290 | const numKeys = keys.length;
|
291 | for (let i = 0; i < numKeys; ++i) {
|
292 | this.slice(keys[i], arg[keys[i]]);
|
293 | }
|
294 | return this;
|
295 | }
|
296 | this._ensurePath('slice');
|
297 | path = this._path;
|
298 | val = arguments[0];
|
299 | } else if (arguments.length === 2) {
|
300 | if ('number' === typeof arguments[0]) {
|
301 | this._ensurePath('slice');
|
302 | path = this._path;
|
303 | val = slice(arguments);
|
304 | } else {
|
305 | path = arguments[0];
|
306 | val = arguments[1];
|
307 | }
|
308 | } else if (arguments.length === 3) {
|
309 | path = arguments[0];
|
310 | val = slice(arguments, 1);
|
311 | }
|
312 |
|
313 | const p = {};
|
314 | p[path] = { $slice: val };
|
315 | this.select(p);
|
316 |
|
317 | return this;
|
318 | };
|
319 |
|
320 |
|
321 | /**
|
322 | * Specifies the complementary comparison value for paths specified with `where()`
|
323 | *
|
324 | * ####Example
|
325 | *
|
326 | * User.where('age').equals(49);
|
327 | *
|
328 | * // is the same as
|
329 | *
|
330 | * User.where('age', 49);
|
331 | *
|
332 | * @method equals
|
333 | * @memberOf Query
|
334 | * @instance
|
335 | * @param {Object} val
|
336 | * @return {Query} this
|
337 | * @api public
|
338 | */
|
339 |
|
340 | /**
|
341 | * Specifies arguments for an `$or` condition.
|
342 | *
|
343 | * ####Example
|
344 | *
|
345 | * query.or([{ color: 'red' }, { status: 'emergency' }])
|
346 | *
|
347 | * @see $or http://docs.mongodb.org/manual/reference/operator/or/
|
348 | * @method or
|
349 | * @memberOf Query
|
350 | * @instance
|
351 | * @param {Array} array array of conditions
|
352 | * @return {Query} this
|
353 | * @api public
|
354 | */
|
355 |
|
356 | /**
|
357 | * Specifies arguments for a `$nor` condition.
|
358 | *
|
359 | * ####Example
|
360 | *
|
361 | * query.nor([{ color: 'green' }, { status: 'ok' }])
|
362 | *
|
363 | * @see $nor http://docs.mongodb.org/manual/reference/operator/nor/
|
364 | * @method nor
|
365 | * @memberOf Query
|
366 | * @instance
|
367 | * @param {Array} array array of conditions
|
368 | * @return {Query} this
|
369 | * @api public
|
370 | */
|
371 |
|
372 | /**
|
373 | * Specifies arguments for a `$and` condition.
|
374 | *
|
375 | * ####Example
|
376 | *
|
377 | * query.and([{ color: 'green' }, { status: 'ok' }])
|
378 | *
|
379 | * @method and
|
380 | * @memberOf Query
|
381 | * @instance
|
382 | * @see $and http://docs.mongodb.org/manual/reference/operator/and/
|
383 | * @param {Array} array array of conditions
|
384 | * @return {Query} this
|
385 | * @api public
|
386 | */
|
387 |
|
388 | /**
|
389 | * Specifies a `$gt` query condition.
|
390 | *
|
391 | * When called with one argument, the most recent path passed to `where()` is used.
|
392 | *
|
393 | * ####Example
|
394 | *
|
395 | * Thing.find().where('age').gt(21)
|
396 | *
|
397 | * // or
|
398 | * Thing.find().gt('age', 21)
|
399 | *
|
400 | * @method gt
|
401 | * @memberOf Query
|
402 | * @instance
|
403 | * @param {String} [path]
|
404 | * @param {Number} val
|
405 | * @see $gt http://docs.mongodb.org/manual/reference/operator/gt/
|
406 | * @api public
|
407 | */
|
408 |
|
409 | /**
|
410 | * Specifies a `$gte` query condition.
|
411 | *
|
412 | * When called with one argument, the most recent path passed to `where()` is used.
|
413 | *
|
414 | * @method gte
|
415 | * @memberOf Query
|
416 | * @instance
|
417 | * @param {String} [path]
|
418 | * @param {Number} val
|
419 | * @see $gte http://docs.mongodb.org/manual/reference/operator/gte/
|
420 | * @api public
|
421 | */
|
422 |
|
423 | /**
|
424 | * Specifies a `$lt` query condition.
|
425 | *
|
426 | * When called with one argument, the most recent path passed to `where()` is used.
|
427 | *
|
428 | * @method lt
|
429 | * @memberOf Query
|
430 | * @instance
|
431 | * @param {String} [path]
|
432 | * @param {Number} val
|
433 | * @see $lt http://docs.mongodb.org/manual/reference/operator/lt/
|
434 | * @api public
|
435 | */
|
436 |
|
437 | /**
|
438 | * Specifies a `$lte` query condition.
|
439 | *
|
440 | * When called with one argument, the most recent path passed to `where()` is used.
|
441 | *
|
442 | * @method lte
|
443 | * @see $lte http://docs.mongodb.org/manual/reference/operator/lte/
|
444 | * @memberOf Query
|
445 | * @instance
|
446 | * @param {String} [path]
|
447 | * @param {Number} val
|
448 | * @api public
|
449 | */
|
450 |
|
451 | /**
|
452 | * Specifies a `$ne` query condition.
|
453 | *
|
454 | * When called with one argument, the most recent path passed to `where()` is used.
|
455 | *
|
456 | * @see $ne http://docs.mongodb.org/manual/reference/operator/ne/
|
457 | * @method ne
|
458 | * @memberOf Query
|
459 | * @instance
|
460 | * @param {String} [path]
|
461 | * @param {Number} val
|
462 | * @api public
|
463 | */
|
464 |
|
465 | /**
|
466 | * Specifies an `$in` query condition.
|
467 | *
|
468 | * When called with one argument, the most recent path passed to `where()` is used.
|
469 | *
|
470 | * @see $in http://docs.mongodb.org/manual/reference/operator/in/
|
471 | * @method in
|
472 | * @memberOf Query
|
473 | * @instance
|
474 | * @param {String} [path]
|
475 | * @param {Number} val
|
476 | * @api public
|
477 | */
|
478 |
|
479 | /**
|
480 | * Specifies an `$nin` query condition.
|
481 | *
|
482 | * When called with one argument, the most recent path passed to `where()` is used.
|
483 | *
|
484 | * @see $nin http://docs.mongodb.org/manual/reference/operator/nin/
|
485 | * @method nin
|
486 | * @memberOf Query
|
487 | * @instance
|
488 | * @param {String} [path]
|
489 | * @param {Number} val
|
490 | * @api public
|
491 | */
|
492 |
|
493 | /**
|
494 | * Specifies an `$all` query condition.
|
495 | *
|
496 | * When called with one argument, the most recent path passed to `where()` is used.
|
497 | *
|
498 | * ####Example:
|
499 | *
|
500 | * MyModel.find().where('pets').all(['dog', 'cat', 'ferret']);
|
501 | * // Equivalent:
|
502 | * MyModel.find().all('pets', ['dog', 'cat', 'ferret']);
|
503 | *
|
504 | * @see $all http://docs.mongodb.org/manual/reference/operator/all/
|
505 | * @method all
|
506 | * @memberOf Query
|
507 | * @instance
|
508 | * @param {String} [path]
|
509 | * @param {Array} val
|
510 | * @api public
|
511 | */
|
512 |
|
513 | /**
|
514 | * Specifies a `$size` query condition.
|
515 | *
|
516 | * When called with one argument, the most recent path passed to `where()` is used.
|
517 | *
|
518 | * ####Example
|
519 | *
|
520 | * MyModel.where('tags').size(0).exec(function (err, docs) {
|
521 | * if (err) return handleError(err);
|
522 | *
|
523 | * assert(Array.isArray(docs));
|
524 | * console.log('documents with 0 tags', docs);
|
525 | * })
|
526 | *
|
527 | * @see $size http://docs.mongodb.org/manual/reference/operator/size/
|
528 | * @method size
|
529 | * @memberOf Query
|
530 | * @instance
|
531 | * @param {String} [path]
|
532 | * @param {Number} val
|
533 | * @api public
|
534 | */
|
535 |
|
536 | /**
|
537 | * Specifies a `$regex` query condition.
|
538 | *
|
539 | * When called with one argument, the most recent path passed to `where()` is used.
|
540 | *
|
541 | * @see $regex http://docs.mongodb.org/manual/reference/operator/regex/
|
542 | * @method regex
|
543 | * @memberOf Query
|
544 | * @instance
|
545 | * @param {String} [path]
|
546 | * @param {String|RegExp} val
|
547 | * @api public
|
548 | */
|
549 |
|
550 | /**
|
551 | * Specifies a `maxDistance` query condition.
|
552 | *
|
553 | * When called with one argument, the most recent path passed to `where()` is used.
|
554 | *
|
555 | * @see $maxDistance http://docs.mongodb.org/manual/reference/operator/maxDistance/
|
556 | * @method maxDistance
|
557 | * @memberOf Query
|
558 | * @instance
|
559 | * @param {String} [path]
|
560 | * @param {Number} val
|
561 | * @api public
|
562 | */
|
563 |
|
564 | /**
|
565 | * Specifies a `$mod` condition, filters documents for documents whose
|
566 | * `path` property is a number that is equal to `remainder` modulo `divisor`.
|
567 | *
|
568 | * ####Example
|
569 | *
|
570 | * // All find products whose inventory is odd
|
571 | * Product.find().mod('inventory', [2, 1]);
|
572 | * Product.find().where('inventory').mod([2, 1]);
|
573 | * // This syntax is a little strange, but supported.
|
574 | * Product.find().where('inventory').mod(2, 1);
|
575 | *
|
576 | * @method mod
|
577 | * @memberOf Query
|
578 | * @instance
|
579 | * @param {String} [path]
|
580 | * @param {Array} val must be of length 2, first element is `divisor`, 2nd element is `remainder`.
|
581 | * @return {Query} this
|
582 | * @see $mod http://docs.mongodb.org/manual/reference/operator/mod/
|
583 | * @api public
|
584 | */
|
585 |
|
586 | Query.prototype.mod = function() {
|
587 | let val;
|
588 | let path;
|
589 |
|
590 | if (arguments.length === 1) {
|
591 | this._ensurePath('mod');
|
592 | val = arguments[0];
|
593 | path = this._path;
|
594 | } else if (arguments.length === 2 && !Array.isArray(arguments[1])) {
|
595 | this._ensurePath('mod');
|
596 | val = slice(arguments);
|
597 | path = this._path;
|
598 | } else if (arguments.length === 3) {
|
599 | val = slice(arguments, 1);
|
600 | path = arguments[0];
|
601 | } else {
|
602 | val = arguments[1];
|
603 | path = arguments[0];
|
604 | }
|
605 |
|
606 | const conds = this._conditions[path] || (this._conditions[path] = {});
|
607 | conds.$mod = val;
|
608 | return this;
|
609 | };
|
610 |
|
611 | /**
|
612 | * Specifies an `$exists` condition
|
613 | *
|
614 | * ####Example
|
615 | *
|
616 | * // { name: { $exists: true }}
|
617 | * Thing.where('name').exists()
|
618 | * Thing.where('name').exists(true)
|
619 | * Thing.find().exists('name')
|
620 | *
|
621 | * // { name: { $exists: false }}
|
622 | * Thing.where('name').exists(false);
|
623 | * Thing.find().exists('name', false);
|
624 | *
|
625 | * @method exists
|
626 | * @memberOf Query
|
627 | * @instance
|
628 | * @param {String} [path]
|
629 | * @param {Number} val
|
630 | * @return {Query} this
|
631 | * @see $exists http://docs.mongodb.org/manual/reference/operator/exists/
|
632 | * @api public
|
633 | */
|
634 |
|
635 | /**
|
636 | * Specifies an `$elemMatch` condition
|
637 | *
|
638 | * ####Example
|
639 | *
|
640 | * query.elemMatch('comment', { author: 'autobot', votes: {$gte: 5}})
|
641 | *
|
642 | * query.where('comment').elemMatch({ author: 'autobot', votes: {$gte: 5}})
|
643 | *
|
644 | * query.elemMatch('comment', function (elem) {
|
645 | * elem.where('author').equals('autobot');
|
646 | * elem.where('votes').gte(5);
|
647 | * })
|
648 | *
|
649 | * query.where('comment').elemMatch(function (elem) {
|
650 | * elem.where({ author: 'autobot' });
|
651 | * elem.where('votes').gte(5);
|
652 | * })
|
653 | *
|
654 | * @method elemMatch
|
655 | * @memberOf Query
|
656 | * @instance
|
657 | * @param {String|Object|Function} path
|
658 | * @param {Object|Function} filter
|
659 | * @return {Query} this
|
660 | * @see $elemMatch http://docs.mongodb.org/manual/reference/operator/elemMatch/
|
661 | * @api public
|
662 | */
|
663 |
|
664 | /**
|
665 | * Defines a `$within` or `$geoWithin` argument for geo-spatial queries.
|
666 | *
|
667 | * ####Example
|
668 | *
|
669 | * query.where(path).within().box()
|
670 | * query.where(path).within().circle()
|
671 | * query.where(path).within().geometry()
|
672 | *
|
673 | * query.where('loc').within({ center: [50,50], radius: 10, unique: true, spherical: true });
|
674 | * query.where('loc').within({ box: [[40.73, -73.9], [40.7, -73.988]] });
|
675 | * query.where('loc').within({ polygon: [[],[],[],[]] });
|
676 | *
|
677 | * query.where('loc').within([], [], []) // polygon
|
678 | * query.where('loc').within([], []) // box
|
679 | * query.where('loc').within({ type: 'LineString', coordinates: [...] }); // geometry
|
680 | *
|
681 | * **MUST** be used after `where()`.
|
682 | *
|
683 | * ####NOTE:
|
684 | *
|
685 | * As of Mongoose 3.7, `$geoWithin` is always used for queries. To change this behavior, see [Query.use$geoWithin](#query_Query-use%2524geoWithin).
|
686 | *
|
687 | * ####NOTE:
|
688 | *
|
689 | * In Mongoose 3.7, `within` changed from a getter to a function. If you need the old syntax, use [this](https://github.com/ebensing/mongoose-within).
|
690 | *
|
691 | * @method within
|
692 | * @see $polygon http://docs.mongodb.org/manual/reference/operator/polygon/
|
693 | * @see $box http://docs.mongodb.org/manual/reference/operator/box/
|
694 | * @see $geometry http://docs.mongodb.org/manual/reference/operator/geometry/
|
695 | * @see $center http://docs.mongodb.org/manual/reference/operator/center/
|
696 | * @see $centerSphere http://docs.mongodb.org/manual/reference/operator/centerSphere/
|
697 | * @memberOf Query
|
698 | * @instance
|
699 | * @return {Query} this
|
700 | * @api public
|
701 | */
|
702 |
|
703 | /**
|
704 | * Specifies a `$slice` projection for an array.
|
705 | *
|
706 | * ####Example
|
707 | *
|
708 | * query.slice('comments', 5)
|
709 | * query.slice('comments', -5)
|
710 | * query.slice('comments', [10, 5])
|
711 | * query.where('comments').slice(5)
|
712 | * query.where('comments').slice([-10, 5])
|
713 | *
|
714 | * @method slice
|
715 | * @memberOf Query
|
716 | * @instance
|
717 | * @param {String} [path]
|
718 | * @param {Number} val number/range of elements to slice
|
719 | * @return {Query} this
|
720 | * @see mongodb http://www.mongodb.org/display/DOCS/Retrieving+a+Subset+of+Fields#RetrievingaSubsetofFields-RetrievingaSubrangeofArrayElements
|
721 | * @see $slice http://docs.mongodb.org/manual/reference/projection/slice/#prj._S_slice
|
722 | * @api public
|
723 | */
|
724 |
|
725 | /**
|
726 | * Specifies the maximum number of documents the query will return.
|
727 | *
|
728 | * ####Example
|
729 | *
|
730 | * query.limit(20)
|
731 | *
|
732 | * ####Note
|
733 | *
|
734 | * Cannot be used with `distinct()`
|
735 | *
|
736 | * @method limit
|
737 | * @memberOf Query
|
738 | * @instance
|
739 | * @param {Number} val
|
740 | * @api public
|
741 | */
|
742 |
|
743 | /**
|
744 | * Specifies the number of documents to skip.
|
745 | *
|
746 | * ####Example
|
747 | *
|
748 | * query.skip(100).limit(20)
|
749 | *
|
750 | * ####Note
|
751 | *
|
752 | * Cannot be used with `distinct()`
|
753 | *
|
754 | * @method skip
|
755 | * @memberOf Query
|
756 | * @instance
|
757 | * @param {Number} val
|
758 | * @see cursor.skip http://docs.mongodb.org/manual/reference/method/cursor.skip/
|
759 | * @api public
|
760 | */
|
761 |
|
762 | /**
|
763 | * Specifies the maxScan option.
|
764 | *
|
765 | * ####Example
|
766 | *
|
767 | * query.maxScan(100)
|
768 | *
|
769 | * ####Note
|
770 | *
|
771 | * Cannot be used with `distinct()`
|
772 | *
|
773 | * @method maxScan
|
774 | * @memberOf Query
|
775 | * @instance
|
776 | * @param {Number} val
|
777 | * @see maxScan http://docs.mongodb.org/manual/reference/operator/maxScan/
|
778 | * @api public
|
779 | */
|
780 |
|
781 | /**
|
782 | * Specifies the batchSize option.
|
783 | *
|
784 | * ####Example
|
785 | *
|
786 | * query.batchSize(100)
|
787 | *
|
788 | * ####Note
|
789 | *
|
790 | * Cannot be used with `distinct()`
|
791 | *
|
792 | * @method batchSize
|
793 | * @memberOf Query
|
794 | * @instance
|
795 | * @param {Number} val
|
796 | * @see batchSize http://docs.mongodb.org/manual/reference/method/cursor.batchSize/
|
797 | * @api public
|
798 | */
|
799 |
|
800 | /**
|
801 | * Specifies the `comment` option.
|
802 | *
|
803 | * ####Example
|
804 | *
|
805 | * query.comment('login query')
|
806 | *
|
807 | * ####Note
|
808 | *
|
809 | * Cannot be used with `distinct()`
|
810 | *
|
811 | * @method comment
|
812 | * @memberOf Query
|
813 | * @instance
|
814 | * @param {String} val
|
815 | * @see comment http://docs.mongodb.org/manual/reference/operator/comment/
|
816 | * @api public
|
817 | */
|
818 |
|
819 | /**
|
820 | * Specifies this query as a `snapshot` query.
|
821 | *
|
822 | * ####Example
|
823 | *
|
824 | * query.snapshot() // true
|
825 | * query.snapshot(true)
|
826 | * query.snapshot(false)
|
827 | *
|
828 | * ####Note
|
829 | *
|
830 | * Cannot be used with `distinct()`
|
831 | *
|
832 | * @method snapshot
|
833 | * @memberOf Query
|
834 | * @instance
|
835 | * @see snapshot http://docs.mongodb.org/manual/reference/operator/snapshot/
|
836 | * @return {Query} this
|
837 | * @api public
|
838 | */
|
839 |
|
840 | /**
|
841 | * Sets query hints.
|
842 | *
|
843 | * ####Example
|
844 | *
|
845 | * query.hint({ indexA: 1, indexB: -1})
|
846 | *
|
847 | * ####Note
|
848 | *
|
849 | * Cannot be used with `distinct()`
|
850 | *
|
851 | * @method hint
|
852 | * @memberOf Query
|
853 | * @instance
|
854 | * @param {Object} val a hint object
|
855 | * @return {Query} this
|
856 | * @see $hint http://docs.mongodb.org/manual/reference/operator/hint/
|
857 | * @api public
|
858 | */
|
859 |
|
860 | /**
|
861 | * Get/set the current projection (AKA fields). Pass `null` to remove the
|
862 | * current projection.
|
863 | *
|
864 | * Unlike `projection()`, the `select()` function modifies the current
|
865 | * projection in place. This function overwrites the existing projection.
|
866 | *
|
867 | * ####Example:
|
868 | *
|
869 | * const q = Model.find();
|
870 | * q.projection(); // null
|
871 | *
|
872 | * q.select('a b');
|
873 | * q.projection(); // { a: 1, b: 1 }
|
874 | *
|
875 | * q.projection({ c: 1 });
|
876 | * q.projection(); // { c: 1 }
|
877 | *
|
878 | * q.projection(null);
|
879 | * q.projection(); // null
|
880 | *
|
881 | *
|
882 | * @method projection
|
883 | * @memberOf Query
|
884 | * @instance
|
885 | * @param {Object|null} arg
|
886 | * @return {Object} the current projection
|
887 | * @api public
|
888 | */
|
889 |
|
890 | Query.prototype.projection = function(arg) {
|
891 | if (arguments.length === 0) {
|
892 | return this._fields;
|
893 | }
|
894 |
|
895 | this._fields = {};
|
896 | this._userProvidedFields = {};
|
897 | this.select(arg);
|
898 | return this._fields;
|
899 | };
|
900 |
|
901 | /**
|
902 | * Specifies which document fields to include or exclude (also known as the query "projection")
|
903 | *
|
904 | * When using string syntax, prefixing a path with `-` will flag that path as excluded. When a path does not have the `-` prefix, it is included. Lastly, if a path is prefixed with `+`, it forces inclusion of the path, which is useful for paths excluded at the [schema level](/docs/api.html#schematype_SchemaType-select).
|
905 | *
|
906 | * A projection _must_ be either inclusive or exclusive. In other words, you must
|
907 | * either list the fields to include (which excludes all others), or list the fields
|
908 | * to exclude (which implies all other fields are included). The [`_id` field is the only exception because MongoDB includes it by default](https://docs.mongodb.com/manual/tutorial/project-fields-from-query-results/#suppress-id-field).
|
909 | *
|
910 | * ####Example
|
911 | *
|
912 | * // include a and b, exclude other fields
|
913 | * query.select('a b');
|
914 | *
|
915 | * // exclude c and d, include other fields
|
916 | * query.select('-c -d');
|
917 | *
|
918 | * // Use `+` to override schema-level `select: false` without making the
|
919 | * // projection inclusive.
|
920 | * const schema = new Schema({
|
921 | * foo: { type: String, select: false },
|
922 | * bar: String
|
923 | * });
|
924 | * // ...
|
925 | * query.select('+foo'); // Override foo's `select: false` without excluding `bar`
|
926 | *
|
927 | * // or you may use object notation, useful when
|
928 | * // you have keys already prefixed with a "-"
|
929 | * query.select({ a: 1, b: 1 });
|
930 | * query.select({ c: 0, d: 0 });
|
931 | *
|
932 | *
|
933 | * @method select
|
934 | * @memberOf Query
|
935 | * @instance
|
936 | * @param {Object|String} arg
|
937 | * @return {Query} this
|
938 | * @see SchemaType
|
939 | * @api public
|
940 | */
|
941 |
|
942 | Query.prototype.select = function select() {
|
943 | let arg = arguments[0];
|
944 | if (!arg) return this;
|
945 | let i;
|
946 |
|
947 | if (arguments.length !== 1) {
|
948 | throw new Error('Invalid select: select only takes 1 argument');
|
949 | }
|
950 |
|
951 | this._validate('select');
|
952 |
|
953 | const fields = this._fields || (this._fields = {});
|
954 | const userProvidedFields = this._userProvidedFields || (this._userProvidedFields = {});
|
955 |
|
956 | arg = parseProjection(arg);
|
957 |
|
958 | if (utils.isObject(arg)) {
|
959 | const keys = Object.keys(arg);
|
960 | for (i = 0; i < keys.length; ++i) {
|
961 | fields[keys[i]] = arg[keys[i]];
|
962 | userProvidedFields[keys[i]] = arg[keys[i]];
|
963 | }
|
964 | return this;
|
965 | }
|
966 |
|
967 | throw new TypeError('Invalid select() argument. Must be string or object.');
|
968 | };
|
969 |
|
970 | /**
|
971 | * _DEPRECATED_ Sets the slaveOk option.
|
972 | *
|
973 | * **Deprecated** in MongoDB 2.2 in favor of [read preferences](#query_Query-read).
|
974 | *
|
975 | * ####Example:
|
976 | *
|
977 | * query.slaveOk() // true
|
978 | * query.slaveOk(true)
|
979 | * query.slaveOk(false)
|
980 | *
|
981 | * @method slaveOk
|
982 | * @memberOf Query
|
983 | * @instance
|
984 | * @deprecated use read() preferences instead if on mongodb >= 2.2
|
985 | * @param {Boolean} v defaults to true
|
986 | * @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference
|
987 | * @see slaveOk http://docs.mongodb.org/manual/reference/method/rs.slaveOk/
|
988 | * @see read() #query_Query-read
|
989 | * @return {Query} this
|
990 | * @api public
|
991 | */
|
992 |
|
993 | /**
|
994 | * Determines the MongoDB nodes from which to read.
|
995 | *
|
996 | * ####Preferences:
|
997 | *
|
998 | * primary - (default) Read from primary only. Operations will produce an error if primary is unavailable. Cannot be combined with tags.
|
999 | * secondary Read from secondary if available, otherwise error.
|
1000 | * primaryPreferred Read from primary if available, otherwise a secondary.
|
1001 | * secondaryPreferred Read from a secondary if available, otherwise read from the primary.
|
1002 | * nearest All operations read from among the nearest candidates, but unlike other modes, this option will include both the primary and all secondaries in the random selection.
|
1003 | *
|
1004 | * Aliases
|
1005 | *
|
1006 | * p primary
|
1007 | * pp primaryPreferred
|
1008 | * s secondary
|
1009 | * sp secondaryPreferred
|
1010 | * n nearest
|
1011 | *
|
1012 | * ####Example:
|
1013 | *
|
1014 | * new Query().read('primary')
|
1015 | * new Query().read('p') // same as primary
|
1016 | *
|
1017 | * new Query().read('primaryPreferred')
|
1018 | * new Query().read('pp') // same as primaryPreferred
|
1019 | *
|
1020 | * new Query().read('secondary')
|
1021 | * new Query().read('s') // same as secondary
|
1022 | *
|
1023 | * new Query().read('secondaryPreferred')
|
1024 | * new Query().read('sp') // same as secondaryPreferred
|
1025 | *
|
1026 | * new Query().read('nearest')
|
1027 | * new Query().read('n') // same as nearest
|
1028 | *
|
1029 | * // read from secondaries with matching tags
|
1030 | * new Query().read('s', [{ dc:'sf', s: 1 },{ dc:'ma', s: 2 }])
|
1031 | *
|
1032 | * Read more about how to use read preferrences [here](http://docs.mongodb.org/manual/applications/replication/#read-preference) and [here](http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences).
|
1033 | *
|
1034 | * @method read
|
1035 | * @memberOf Query
|
1036 | * @instance
|
1037 | * @param {String} pref one of the listed preference options or aliases
|
1038 | * @param {Array} [tags] optional tags for this query
|
1039 | * @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference
|
1040 | * @see driver http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences
|
1041 | * @return {Query} this
|
1042 | * @api public
|
1043 | */
|
1044 |
|
1045 | Query.prototype.read = function read(pref, tags) {
|
1046 | // first cast into a ReadPreference object to support tags
|
1047 | const read = new ReadPreference(pref, tags);
|
1048 | this.options.readPreference = read;
|
1049 | return this;
|
1050 | };
|
1051 |
|
1052 | /**
|
1053 | * Sets the [MongoDB session](https://docs.mongodb.com/manual/reference/server-sessions/)
|
1054 | * associated with this query. Sessions are how you mark a query as part of a
|
1055 | * [transaction](/docs/transactions.html).
|
1056 | *
|
1057 | * Calling `session(null)` removes the session from this query.
|
1058 | *
|
1059 | * ####Example:
|
1060 | *
|
1061 | * const s = await mongoose.startSession();
|
1062 | * await mongoose.model('Person').findOne({ name: 'Axl Rose' }).session(s);
|
1063 | *
|
1064 | * @method session
|
1065 | * @memberOf Query
|
1066 | * @instance
|
1067 | * @param {ClientSession} [session] from `await conn.startSession()`
|
1068 | * @see Connection.prototype.startSession() /docs/api.html#connection_Connection-startSession
|
1069 | * @see mongoose.startSession() /docs/api.html#mongoose_Mongoose-startSession
|
1070 | * @return {Query} this
|
1071 | * @api public
|
1072 | */
|
1073 |
|
1074 | Query.prototype.session = function session(v) {
|
1075 | if (v == null) {
|
1076 | delete this.options.session;
|
1077 | }
|
1078 | this.options.session = v;
|
1079 | return this;
|
1080 | };
|
1081 |
|
1082 | /**
|
1083 | * Sets the specified number of `mongod` servers, or tag set of `mongod` servers,
|
1084 | * that must acknowledge this write before this write is considered successful.
|
1085 | * This option is only valid for operations that write to the database:
|
1086 | *
|
1087 | * - `deleteOne()`
|
1088 | * - `deleteMany()`
|
1089 | * - `findOneAndDelete()`
|
1090 | * - `findOneAndReplace()`
|
1091 | * - `findOneAndUpdate()`
|
1092 | * - `remove()`
|
1093 | * - `update()`
|
1094 | * - `updateOne()`
|
1095 | * - `updateMany()`
|
1096 | *
|
1097 | * Defaults to the schema's [`writeConcern.w` option](/docs/guide.html#writeConcern)
|
1098 | *
|
1099 | * ####Example:
|
1100 | *
|
1101 | * // The 'majority' option means the `deleteOne()` promise won't resolve
|
1102 | * // until the `deleteOne()` has propagated to the majority of the replica set
|
1103 | * await mongoose.model('Person').
|
1104 | * deleteOne({ name: 'Ned Stark' }).
|
1105 | * w('majority');
|
1106 | *
|
1107 | * @method w
|
1108 | * @memberOf Query
|
1109 | * @instance
|
1110 | * @param {String|number} val 0 for fire-and-forget, 1 for acknowledged by one server, 'majority' for majority of the replica set, or [any of the more advanced options](https://docs.mongodb.com/manual/reference/write-concern/#w-option).
|
1111 | * @see mongodb https://docs.mongodb.com/manual/reference/write-concern/#w-option
|
1112 | * @return {Query} this
|
1113 | * @api public
|
1114 | */
|
1115 |
|
1116 | Query.prototype.w = function w(val) {
|
1117 | if (val == null) {
|
1118 | delete this.options.w;
|
1119 | }
|
1120 | this.options.w = val;
|
1121 | return this;
|
1122 | };
|
1123 |
|
1124 | /**
|
1125 | * Requests acknowledgement that this operation has been persisted to MongoDB's
|
1126 | * on-disk journal.
|
1127 | * This option is only valid for operations that write to the database:
|
1128 | *
|
1129 | * - `deleteOne()`
|
1130 | * - `deleteMany()`
|
1131 | * - `findOneAndDelete()`
|
1132 | * - `findOneAndReplace()`
|
1133 | * - `findOneAndUpdate()`
|
1134 | * - `remove()`
|
1135 | * - `update()`
|
1136 | * - `updateOne()`
|
1137 | * - `updateMany()`
|
1138 | *
|
1139 | * Defaults to the schema's [`writeConcern.j` option](/docs/guide.html#writeConcern)
|
1140 | *
|
1141 | * ####Example:
|
1142 | *
|
1143 | * await mongoose.model('Person').deleteOne({ name: 'Ned Stark' }).j(true);
|
1144 | *
|
1145 | * @method j
|
1146 | * @memberOf Query
|
1147 | * @instance
|
1148 | * @param {boolean} val
|
1149 | * @see mongodb https://docs.mongodb.com/manual/reference/write-concern/#j-option
|
1150 | * @return {Query} this
|
1151 | * @api public
|
1152 | */
|
1153 |
|
1154 | Query.prototype.j = function j(val) {
|
1155 | if (val == null) {
|
1156 | delete this.options.j;
|
1157 | }
|
1158 | this.options.j = val;
|
1159 | return this;
|
1160 | };
|
1161 |
|
1162 | /**
|
1163 | * If [`w > 1`](/docs/api.html#query_Query-w), the maximum amount of time to
|
1164 | * wait for this write to propagate through the replica set before this
|
1165 | * operation fails. The default is `0`, which means no timeout.
|
1166 | *
|
1167 | * This option is only valid for operations that write to the database:
|
1168 | *
|
1169 | * - `deleteOne()`
|
1170 | * - `deleteMany()`
|
1171 | * - `findOneAndDelete()`
|
1172 | * - `findOneAndReplace()`
|
1173 | * - `findOneAndUpdate()`
|
1174 | * - `remove()`
|
1175 | * - `update()`
|
1176 | * - `updateOne()`
|
1177 | * - `updateMany()`
|
1178 | *
|
1179 | * Defaults to the schema's [`writeConcern.wtimeout` option](/docs/guide.html#writeConcern)
|
1180 | *
|
1181 | * ####Example:
|
1182 | *
|
1183 | * // The `deleteOne()` promise won't resolve until this `deleteOne()` has
|
1184 | * // propagated to at least `w = 2` members of the replica set. If it takes
|
1185 | * // longer than 1 second, this `deleteOne()` will fail.
|
1186 | * await mongoose.model('Person').
|
1187 | * deleteOne({ name: 'Ned Stark' }).
|
1188 | * w(2).
|
1189 | * wtimeout(1000);
|
1190 | *
|
1191 | * @method wtimeout
|
1192 | * @memberOf Query
|
1193 | * @instance
|
1194 | * @param {number} ms number of milliseconds to wait
|
1195 | * @see mongodb https://docs.mongodb.com/manual/reference/write-concern/#wtimeout
|
1196 | * @return {Query} this
|
1197 | * @api public
|
1198 | */
|
1199 |
|
1200 | Query.prototype.wtimeout = function wtimeout(ms) {
|
1201 | if (ms == null) {
|
1202 | delete this.options.wtimeout;
|
1203 | }
|
1204 | this.options.wtimeout = ms;
|
1205 | return this;
|
1206 | };
|
1207 |
|
1208 | /**
|
1209 | * Sets the readConcern option for the query.
|
1210 | *
|
1211 | * ####Example:
|
1212 | *
|
1213 | * new Query().readConcern('local')
|
1214 | * new Query().readConcern('l') // same as local
|
1215 | *
|
1216 | * new Query().readConcern('available')
|
1217 | * new Query().readConcern('a') // same as available
|
1218 | *
|
1219 | * new Query().readConcern('majority')
|
1220 | * new Query().readConcern('m') // same as majority
|
1221 | *
|
1222 | * new Query().readConcern('linearizable')
|
1223 | * new Query().readConcern('lz') // same as linearizable
|
1224 | *
|
1225 | * new Query().readConcern('snapshot')
|
1226 | * new Query().readConcern('s') // same as snapshot
|
1227 | *
|
1228 | *
|
1229 | * ####Read Concern Level:
|
1230 | *
|
1231 | * local MongoDB 3.2+ The query returns from the instance with no guarantee guarantee that the data has been written to a majority of the replica set members (i.e. may be rolled back).
|
1232 | * available MongoDB 3.6+ The query returns from the instance with no guarantee guarantee that the data has been written to a majority of the replica set members (i.e. may be rolled back).
|
1233 | * majority MongoDB 3.2+ The query returns the data that has been acknowledged by a majority of the replica set members. The documents returned by the read operation are durable, even in the event of failure.
|
1234 | * linearizable MongoDB 3.4+ The query returns data that reflects all successful majority-acknowledged writes that completed prior to the start of the read operation. The query may wait for concurrently executing writes to propagate to a majority of replica set members before returning results.
|
1235 | * snapshot MongoDB 4.0+ Only available for operations within multi-document transactions. Upon transaction commit with write concern "majority", the transaction operations are guaranteed to have read from a snapshot of majority-committed data.
|
1236 | *
|
1237 | * Aliases
|
1238 | *
|
1239 | * l local
|
1240 | * a available
|
1241 | * m majority
|
1242 | * lz linearizable
|
1243 | * s snapshot
|
1244 | *
|
1245 | * Read more about how to use read concern [here](https://docs.mongodb.com/manual/reference/read-concern/).
|
1246 | *
|
1247 | * @memberOf Query
|
1248 | * @method readConcern
|
1249 | * @param {String} level one of the listed read concern level or their aliases
|
1250 | * @see mongodb https://docs.mongodb.com/manual/reference/read-concern/
|
1251 | * @return {Query} this
|
1252 | * @api public
|
1253 | */
|
1254 |
|
1255 | /**
|
1256 | * Gets query options.
|
1257 | *
|
1258 | * ####Example:
|
1259 | *
|
1260 | * var query = new Query();
|
1261 | * query.limit(10);
|
1262 | * query.setOptions({ maxTimeMS: 1000 })
|
1263 | * query.getOptions(); // { limit: 10, maxTimeMS: 1000 }
|
1264 | *
|
1265 | * @return {Object} the options
|
1266 | * @api public
|
1267 | */
|
1268 |
|
1269 | Query.prototype.getOptions = function() {
|
1270 | return this.options;
|
1271 | };
|
1272 |
|
1273 | /**
|
1274 | * Sets query options. Some options only make sense for certain operations.
|
1275 | *
|
1276 | * ####Options:
|
1277 | *
|
1278 | * The following options are only for `find()`:
|
1279 | *
|
1280 | * - [tailable](http://www.mongodb.org/display/DOCS/Tailable+Cursors)
|
1281 | * - [sort](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsort(\)%7D%7D)
|
1282 | * - [limit](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Blimit%28%29%7D%7D)
|
1283 | * - [skip](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bskip%28%29%7D%7D)
|
1284 | * - [maxscan](https://docs.mongodb.org/v3.2/reference/operator/meta/maxScan/#metaOp._S_maxScan)
|
1285 | * - [batchSize](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7BbatchSize%28%29%7D%7D)
|
1286 | * - [comment](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24comment)
|
1287 | * - [snapshot](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsnapshot%28%29%7D%7D)
|
1288 | * - [readPreference](http://docs.mongodb.org/manual/applications/replication/#read-preference)
|
1289 | * - [hint](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24hint)
|
1290 | *
|
1291 | * The following options are only for write operations: `update()`, `updateOne()`, `updateMany()`, `replaceOne()`, `findOneAndUpdate()`, and `findByIdAndUpdate()`:
|
1292 | *
|
1293 | * - [upsert](https://docs.mongodb.com/manual/reference/method/db.collection.update/)
|
1294 | * - [writeConcern](https://docs.mongodb.com/manual/reference/method/db.collection.update/)
|
1295 | * - [timestamps](https://mongoosejs.com/docs/guide.html#timestamps): If `timestamps` is set in the schema, set this option to `false` to skip timestamps for that particular update. Has no effect if `timestamps` is not enabled in the schema options.
|
1296 | * - omitUndefined: delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server.
|
1297 | *
|
1298 | * The following options are only for `find()`, `findOne()`, `findById()`, `findOneAndUpdate()`, and `findByIdAndUpdate()`:
|
1299 | *
|
1300 | * - [lean](./api.html#query_Query-lean)
|
1301 | * - [populate](/docs/populate.html)
|
1302 | * - [projection](/docs/api/query.html#query_Query-projection)
|
1303 | *
|
1304 | * The following options are only for all operations **except** `update()`, `updateOne()`, `updateMany()`, `remove()`, `deleteOne()`, and `deleteMany()`:
|
1305 | *
|
1306 | * - [maxTimeMS](https://docs.mongodb.com/manual/reference/operator/meta/maxTimeMS/)
|
1307 | *
|
1308 | * The following options are for `findOneAndUpdate()` and `findOneAndRemove()`
|
1309 | *
|
1310 | * - [useFindAndModify](/docs/deprecations.html#findandmodify)
|
1311 | * - rawResult
|
1312 | *
|
1313 | * The following options are for all operations:
|
1314 | *
|
1315 | * - [collation](https://docs.mongodb.com/manual/reference/collation/)
|
1316 | * - [session](https://docs.mongodb.com/manual/reference/server-sessions/)
|
1317 | * - [explain](https://docs.mongodb.com/manual/reference/method/cursor.explain/)
|
1318 | *
|
1319 | * @param {Object} options
|
1320 | * @return {Query} this
|
1321 | * @api public
|
1322 | */
|
1323 |
|
1324 | Query.prototype.setOptions = function(options, overwrite) {
|
1325 | // overwrite is only for internal use
|
1326 | if (overwrite) {
|
1327 | // ensure that _mongooseOptions & options are two different objects
|
1328 | this._mongooseOptions = (options && utils.clone(options)) || {};
|
1329 | this.options = options || {};
|
1330 |
|
1331 | if ('populate' in options) {
|
1332 | this.populate(this._mongooseOptions);
|
1333 | }
|
1334 | return this;
|
1335 | }
|
1336 |
|
1337 | if (options == null) {
|
1338 | return this;
|
1339 | }
|
1340 | if (typeof options !== 'object') {
|
1341 | throw new Error('Options must be an object, got "' + options + '"');
|
1342 | }
|
1343 |
|
1344 | if (Array.isArray(options.populate)) {
|
1345 | const populate = options.populate;
|
1346 | delete options.populate;
|
1347 | const _numPopulate = populate.length;
|
1348 | for (let i = 0; i < _numPopulate; ++i) {
|
1349 | this.populate(populate[i]);
|
1350 | }
|
1351 | }
|
1352 |
|
1353 | if ('useFindAndModify' in options) {
|
1354 | this._mongooseOptions.useFindAndModify = options.useFindAndModify;
|
1355 | delete options.useFindAndModify;
|
1356 | }
|
1357 | if ('omitUndefined' in options) {
|
1358 | this._mongooseOptions.omitUndefined = options.omitUndefined;
|
1359 | delete options.omitUndefined;
|
1360 | }
|
1361 |
|
1362 | return Query.base.setOptions.call(this, options);
|
1363 | };
|
1364 |
|
1365 | /**
|
1366 | * Sets the [`explain` option](https://docs.mongodb.com/manual/reference/method/cursor.explain/),
|
1367 | * which makes this query return detailed execution stats instead of the actual
|
1368 | * query result. This method is useful for determining what index your queries
|
1369 | * use.
|
1370 | *
|
1371 | * Calling `query.explain(v)` is equivalent to `query.setOption({ explain: v })`
|
1372 | *
|
1373 | * ####Example:
|
1374 | *
|
1375 | * const query = new Query();
|
1376 | * const res = await query.find({ a: 1 }).explain('queryPlanner');
|
1377 | * console.log(res);
|
1378 | *
|
1379 | * @param {String} [verbose] The verbosity mode. Either 'queryPlanner', 'executionStats', or 'allPlansExecution'. The default is 'queryPlanner'
|
1380 | * @return {Query} this
|
1381 | * @api public
|
1382 | */
|
1383 |
|
1384 | Query.prototype.explain = function(verbose) {
|
1385 | if (arguments.length === 0) {
|
1386 | this.options.explain = true;
|
1387 | return this;
|
1388 | }
|
1389 | this.options.explain = verbose;
|
1390 | return this;
|
1391 | };
|
1392 |
|
1393 | /**
|
1394 | * Sets the [maxTimeMS](https://docs.mongodb.com/manual/reference/method/cursor.maxTimeMS/)
|
1395 | * option. This will tell the MongoDB server to abort if the query or write op
|
1396 | * has been running for more than `ms` milliseconds.
|
1397 | *
|
1398 | * Calling `query.maxTimeMS(v)` is equivalent to `query.setOption({ maxTimeMS: v })`
|
1399 | *
|
1400 | * ####Example:
|
1401 | *
|
1402 | * const query = new Query();
|
1403 | * // Throws an error 'operation exceeded time limit' as long as there's
|
1404 | * // >= 1 doc in the queried collection
|
1405 | * const res = await query.find({ $where: 'sleep(1000) || true' }).maxTimeMS(100);
|
1406 | *
|
1407 | * @param {Number} [ms] The number of milliseconds
|
1408 | * @return {Query} this
|
1409 | * @api public
|
1410 | */
|
1411 |
|
1412 | Query.prototype.maxTimeMS = function(ms) {
|
1413 | this.options.maxTimeMS = ms;
|
1414 | return this;
|
1415 | };
|
1416 |
|
1417 | /**
|
1418 | * Returns the current query filter (also known as conditions) as a POJO.
|
1419 | *
|
1420 | * ####Example:
|
1421 | *
|
1422 | * const query = new Query();
|
1423 | * query.find({ a: 1 }).where('b').gt(2);
|
1424 | * query.getFilter(); // { a: 1, b: { $gt: 2 } }
|
1425 | *
|
1426 | * @return {Object} current query filter
|
1427 | * @api public
|
1428 | */
|
1429 |
|
1430 | Query.prototype.getFilter = function() {
|
1431 | return this._conditions;
|
1432 | };
|
1433 |
|
1434 | /**
|
1435 | * Returns the current query filter. Equivalent to `getFilter()`.
|
1436 | *
|
1437 | * You should use `getFilter()` instead of `getQuery()` where possible. `getQuery()`
|
1438 | * will likely be deprecated in a future release.
|
1439 | *
|
1440 | * ####Example:
|
1441 | *
|
1442 | * var query = new Query();
|
1443 | * query.find({ a: 1 }).where('b').gt(2);
|
1444 | * query.getQuery(); // { a: 1, b: { $gt: 2 } }
|
1445 | *
|
1446 | * @return {Object} current query filter
|
1447 | * @api public
|
1448 | */
|
1449 |
|
1450 | Query.prototype.getQuery = function() {
|
1451 | return this._conditions;
|
1452 | };
|
1453 |
|
1454 | /**
|
1455 | * Sets the query conditions to the provided JSON object.
|
1456 | *
|
1457 | * ####Example:
|
1458 | *
|
1459 | * var query = new Query();
|
1460 | * query.find({ a: 1 })
|
1461 | * query.setQuery({ a: 2 });
|
1462 | * query.getQuery(); // { a: 2 }
|
1463 | *
|
1464 | * @param {Object} new query conditions
|
1465 | * @return {undefined}
|
1466 | * @api public
|
1467 | */
|
1468 |
|
1469 | Query.prototype.setQuery = function(val) {
|
1470 | this._conditions = val;
|
1471 | };
|
1472 |
|
1473 | /**
|
1474 | * Returns the current update operations as a JSON object.
|
1475 | *
|
1476 | * ####Example:
|
1477 | *
|
1478 | * var query = new Query();
|
1479 | * query.update({}, { $set: { a: 5 } });
|
1480 | * query.getUpdate(); // { $set: { a: 5 } }
|
1481 | *
|
1482 | * @return {Object} current update operations
|
1483 | * @api public
|
1484 | */
|
1485 |
|
1486 | Query.prototype.getUpdate = function() {
|
1487 | return this._update;
|
1488 | };
|
1489 |
|
1490 | /**
|
1491 | * Sets the current update operation to new value.
|
1492 | *
|
1493 | * ####Example:
|
1494 | *
|
1495 | * var query = new Query();
|
1496 | * query.update({}, { $set: { a: 5 } });
|
1497 | * query.setUpdate({ $set: { b: 6 } });
|
1498 | * query.getUpdate(); // { $set: { b: 6 } }
|
1499 | *
|
1500 | * @param {Object} new update operation
|
1501 | * @return {undefined}
|
1502 | * @api public
|
1503 | */
|
1504 |
|
1505 | Query.prototype.setUpdate = function(val) {
|
1506 | this._update = val;
|
1507 | };
|
1508 |
|
1509 | /**
|
1510 | * Returns fields selection for this query.
|
1511 | *
|
1512 | * @method _fieldsForExec
|
1513 | * @return {Object}
|
1514 | * @api private
|
1515 | * @receiver Query
|
1516 | */
|
1517 |
|
1518 | Query.prototype._fieldsForExec = function() {
|
1519 | return utils.clone(this._fields);
|
1520 | };
|
1521 |
|
1522 |
|
1523 | /**
|
1524 | * Return an update document with corrected `$set` operations.
|
1525 | *
|
1526 | * @method _updateForExec
|
1527 | * @api private
|
1528 | * @receiver Query
|
1529 | */
|
1530 |
|
1531 | Query.prototype._updateForExec = function() {
|
1532 | const update = utils.clone(this._update, {
|
1533 | transform: false,
|
1534 | depopulate: true
|
1535 | });
|
1536 | const ops = Object.keys(update);
|
1537 | let i = ops.length;
|
1538 | const ret = {};
|
1539 |
|
1540 | while (i--) {
|
1541 | const op = ops[i];
|
1542 |
|
1543 | if (this.options.overwrite) {
|
1544 | ret[op] = update[op];
|
1545 | continue;
|
1546 | }
|
1547 |
|
1548 | if ('$' !== op[0]) {
|
1549 | // fix up $set sugar
|
1550 | if (!ret.$set) {
|
1551 | if (update.$set) {
|
1552 | ret.$set = update.$set;
|
1553 | } else {
|
1554 | ret.$set = {};
|
1555 | }
|
1556 | }
|
1557 | ret.$set[op] = update[op];
|
1558 | ops.splice(i, 1);
|
1559 | if (!~ops.indexOf('$set')) ops.push('$set');
|
1560 | } else if ('$set' === op) {
|
1561 | if (!ret.$set) {
|
1562 | ret[op] = update[op];
|
1563 | }
|
1564 | } else {
|
1565 | ret[op] = update[op];
|
1566 | }
|
1567 | }
|
1568 |
|
1569 | return ret;
|
1570 | };
|
1571 |
|
1572 | /**
|
1573 | * Makes sure _path is set.
|
1574 | *
|
1575 | * @method _ensurePath
|
1576 | * @param {String} method
|
1577 | * @api private
|
1578 | * @receiver Query
|
1579 | */
|
1580 |
|
1581 | /**
|
1582 | * Determines if `conds` can be merged using `mquery().merge()`
|
1583 | *
|
1584 | * @method canMerge
|
1585 | * @memberOf Query
|
1586 | * @instance
|
1587 | * @param {Object} conds
|
1588 | * @return {Boolean}
|
1589 | * @api private
|
1590 | */
|
1591 |
|
1592 | /**
|
1593 | * Returns default options for this query.
|
1594 | *
|
1595 | * @param {Model} model
|
1596 | * @api private
|
1597 | */
|
1598 |
|
1599 | Query.prototype._optionsForExec = function(model) {
|
1600 | const options = utils.clone(this.options);
|
1601 |
|
1602 | delete options.populate;
|
1603 | model = model || this.model;
|
1604 |
|
1605 | if (!model) {
|
1606 | return options;
|
1607 | }
|
1608 |
|
1609 | const safe = get(model, 'schema.options.safe', null);
|
1610 | if (!('safe' in options) && safe != null) {
|
1611 | setSafe(options, safe);
|
1612 | }
|
1613 |
|
1614 | // Apply schema-level `writeConcern` option
|
1615 | applyWriteConcern(model.schema, options);
|
1616 |
|
1617 | const readPreference = get(model, 'schema.options.read');
|
1618 | if (!('readPreference' in options) && readPreference) {
|
1619 | options.readPreference = readPreference;
|
1620 | }
|
1621 |
|
1622 | if (options.upsert !== void 0) {
|
1623 | options.upsert = !!options.upsert;
|
1624 | }
|
1625 |
|
1626 | return options;
|
1627 | };
|
1628 |
|
1629 | /*!
|
1630 | * ignore
|
1631 | */
|
1632 |
|
1633 | const safeDeprecationWarning = 'Mongoose: the `safe` option is deprecated. ' +
|
1634 | 'Use write concerns instead: http://bit.ly/mongoose-w';
|
1635 |
|
1636 | const setSafe = util.deprecate(function setSafe(options, safe) {
|
1637 | options.safe = safe;
|
1638 | }, safeDeprecationWarning);
|
1639 |
|
1640 | /**
|
1641 | * Sets the lean option.
|
1642 | *
|
1643 | * Documents returned from queries with the `lean` option enabled are plain
|
1644 | * javascript objects, not [Mongoose Documents](#document-js). They have no
|
1645 | * `save` method, getters/setters, virtuals, or other Mongoose features.
|
1646 | *
|
1647 | * ####Example:
|
1648 | *
|
1649 | * new Query().lean() // true
|
1650 | * new Query().lean(true)
|
1651 | * new Query().lean(false)
|
1652 | *
|
1653 | * const docs = await Model.find().lean();
|
1654 | * docs[0] instanceof mongoose.Document; // false
|
1655 | *
|
1656 | * [Lean is great for high-performance, read-only cases](/docs/tutorials/lean.html),
|
1657 | * especially when combined
|
1658 | * with [cursors](/docs/queries.html#streaming).
|
1659 | *
|
1660 | * If you need virtuals, getters/setters, or defaults with `lean()`, you need
|
1661 | * to use a plugin. See:
|
1662 | *
|
1663 | * - [mongoose-lean-virtuals](https://plugins.mongoosejs.io/plugins/lean-virtuals)
|
1664 | * - [mongoose-lean-getters](https://plugins.mongoosejs.io/plugins/lean-getters)
|
1665 | * - [mongoose-lean-defaults](https://www.npmjs.com/package/mongoose-lean-defaults)
|
1666 | *
|
1667 | * @param {Boolean|Object} bool defaults to true
|
1668 | * @return {Query} this
|
1669 | * @api public
|
1670 | */
|
1671 |
|
1672 | Query.prototype.lean = function(v) {
|
1673 | this._mongooseOptions.lean = arguments.length ? v : true;
|
1674 | return this;
|
1675 | };
|
1676 |
|
1677 | /**
|
1678 | * Returns an object containing the Mongoose-specific options for this query,
|
1679 | * including `lean` and `populate`.
|
1680 | *
|
1681 | * Mongoose-specific options are different from normal options (`sort`, `limit`, etc.)
|
1682 | * because they are **not** sent to the MongoDB server.
|
1683 | *
|
1684 | * ####Example:
|
1685 | *
|
1686 | * const q = new Query();
|
1687 | * q.mongooseOptions().lean; // undefined
|
1688 | *
|
1689 | * q.lean();
|
1690 | * q.mongooseOptions().lean; // true
|
1691 | *
|
1692 | * This function is useful for writing [query middleware](/docs/middleware.html).
|
1693 | * Below is a full list of properties the return value from this function may have:
|
1694 | *
|
1695 | * - `populate`
|
1696 | * - `lean`
|
1697 | * - `omitUndefined`
|
1698 | * - `strict`
|
1699 | * - `nearSphere`
|
1700 | * - `useFindAndModify`
|
1701 | *
|
1702 | * @return {Object} Mongoose-specific options
|
1703 | * @param public
|
1704 | */
|
1705 |
|
1706 | Query.prototype.mongooseOptions = function() {
|
1707 | return this._mongooseOptions;
|
1708 | };
|
1709 |
|
1710 | /**
|
1711 | * Adds a `$set` to this query's update without changing the operation.
|
1712 | * This is useful for query middleware so you can add an update regardless
|
1713 | * of whether you use `updateOne()`, `updateMany()`, `findOneAndUpdate()`, etc.
|
1714 | *
|
1715 | * ####Example:
|
1716 | *
|
1717 | * // Updates `{ $set: { updatedAt: new Date() } }`
|
1718 | * new Query().updateOne({}, {}).set('updatedAt', new Date());
|
1719 | * new Query().updateMany({}, {}).set({ updatedAt: new Date() });
|
1720 | *
|
1721 | * @param {String|Object} path path or object of key/value pairs to set
|
1722 | * @param {Any} [val] the value to set
|
1723 | * @return {Query} this
|
1724 | * @api public
|
1725 | */
|
1726 |
|
1727 | Query.prototype.set = function(path, val) {
|
1728 | if (typeof path === 'object') {
|
1729 | const keys = Object.keys(path);
|
1730 | for (const key of keys) {
|
1731 | this.set(key, path[key]);
|
1732 | }
|
1733 | return this;
|
1734 | }
|
1735 |
|
1736 | this._update = this._update || {};
|
1737 | this._update.$set = this._update.$set || {};
|
1738 | this._update.$set[path] = val;
|
1739 | return this;
|
1740 | };
|
1741 |
|
1742 | /**
|
1743 | * For update operations, returns the value of a path in the update's `$set`.
|
1744 | * Useful for writing getters/setters that can work with both update operations
|
1745 | * and `save()`.
|
1746 | *
|
1747 | * ####Example:
|
1748 | *
|
1749 | * const query = Model.updateOne({}, { $set: { name: 'Jean-Luc Picard' } });
|
1750 | * query.get('name'); // 'Jean-Luc Picard'
|
1751 | *
|
1752 | * @param {String|Object} path path or object of key/value pairs to set
|
1753 | * @param {Any} [val] the value to set
|
1754 | * @return {Query} this
|
1755 | * @api public
|
1756 | */
|
1757 |
|
1758 | Query.prototype.get = function get(path) {
|
1759 | const update = this._update;
|
1760 | if (update == null) {
|
1761 | return void 0;
|
1762 | }
|
1763 | const $set = update.$set;
|
1764 | if ($set == null) {
|
1765 | return update[path];
|
1766 | }
|
1767 |
|
1768 | if (utils.hasUserDefinedProperty(update, path)) {
|
1769 | return update[path];
|
1770 | }
|
1771 | if (utils.hasUserDefinedProperty($set, path)) {
|
1772 | return $set[path];
|
1773 | }
|
1774 |
|
1775 | return void 0;
|
1776 | };
|
1777 |
|
1778 | /**
|
1779 | * Gets/sets the error flag on this query. If this flag is not null or
|
1780 | * undefined, the `exec()` promise will reject without executing.
|
1781 | *
|
1782 | * ####Example:
|
1783 | *
|
1784 | * Query().error(); // Get current error value
|
1785 | * Query().error(null); // Unset the current error
|
1786 | * Query().error(new Error('test')); // `exec()` will resolve with test
|
1787 | * Schema.pre('find', function() {
|
1788 | * if (!this.getQuery().userId) {
|
1789 | * this.error(new Error('Not allowed to query without setting userId'));
|
1790 | * }
|
1791 | * });
|
1792 | *
|
1793 | * Note that query casting runs **after** hooks, so cast errors will override
|
1794 | * custom errors.
|
1795 | *
|
1796 | * ####Example:
|
1797 | * var TestSchema = new Schema({ num: Number });
|
1798 | * var TestModel = db.model('Test', TestSchema);
|
1799 | * TestModel.find({ num: 'not a number' }).error(new Error('woops')).exec(function(error) {
|
1800 | * // `error` will be a cast error because `num` failed to cast
|
1801 | * });
|
1802 | *
|
1803 | * @param {Error|null} err if set, `exec()` will fail fast before sending the query to MongoDB
|
1804 | * @return {Query} this
|
1805 | * @api public
|
1806 | */
|
1807 |
|
1808 | Query.prototype.error = function error(err) {
|
1809 | if (arguments.length === 0) {
|
1810 | return this._error;
|
1811 | }
|
1812 |
|
1813 | this._error = err;
|
1814 | return this;
|
1815 | };
|
1816 |
|
1817 | /*!
|
1818 | * ignore
|
1819 | */
|
1820 |
|
1821 | Query.prototype._unsetCastError = function _unsetCastError() {
|
1822 | if (this._error != null && !(this._error instanceof CastError)) {
|
1823 | return;
|
1824 | }
|
1825 | return this.error(null);
|
1826 | };
|
1827 |
|
1828 | /**
|
1829 | * Getter/setter around the current mongoose-specific options for this query
|
1830 | * Below are the current Mongoose-specific options.
|
1831 | *
|
1832 | * - `populate`: an array representing what paths will be populated. Should have one entry for each call to [`Query.prototype.populate()`](/docs/api.html#query_Query-populate)
|
1833 | * - `lean`: if truthy, Mongoose will not [hydrate](/docs/api.html#model_Model.hydrate) any documents that are returned from this query. See [`Query.prototype.lean()`](/docs/api.html#query_Query-lean) for more information.
|
1834 | * - `strict`: controls how Mongoose handles keys that aren't in the schema for updates. This option is `true` by default, which means Mongoose will silently strip any paths in the update that aren't in the schema. See the [`strict` mode docs](/docs/guide.html#strict) for more information.
|
1835 | * - `strictQuery`: controls how Mongoose handles keys that aren't in the schema for the query `filter`. This option is `false` by default for backwards compatibility, which means Mongoose will allow `Model.find({ foo: 'bar' })` even if `foo` is not in the schema. See the [`strictQuery` docs](/docs/guide.html#strictQuery) for more information.
|
1836 | * - `useFindAndModify`: used to work around the [`findAndModify()` deprecation warning](/docs/deprecations.html#-findandmodify-)
|
1837 | * - `omitUndefined`: delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server.
|
1838 | * - `nearSphere`: use `$nearSphere` instead of `near()`. See the [`Query.prototype.nearSphere()` docs](/docs/api.html#query_Query-nearSphere)
|
1839 | *
|
1840 | * Mongoose maintains a separate object for internal options because
|
1841 | * Mongoose sends `Query.prototype.options` to the MongoDB server, and the
|
1842 | * above options are not relevant for the MongoDB server.
|
1843 | *
|
1844 | * @param {Object} options if specified, overwrites the current options
|
1845 | * @return {Object} the options
|
1846 | * @api public
|
1847 | */
|
1848 |
|
1849 | Query.prototype.mongooseOptions = function(v) {
|
1850 | if (arguments.length > 0) {
|
1851 | this._mongooseOptions = v;
|
1852 | }
|
1853 | return this._mongooseOptions;
|
1854 | };
|
1855 |
|
1856 | /*!
|
1857 | * ignore
|
1858 | */
|
1859 |
|
1860 | Query.prototype._castConditions = function() {
|
1861 | try {
|
1862 | this.cast(this.model);
|
1863 | this._unsetCastError();
|
1864 | } catch (err) {
|
1865 | this.error(err);
|
1866 | }
|
1867 | };
|
1868 |
|
1869 | /*!
|
1870 | * ignore
|
1871 | */
|
1872 |
|
1873 | function _castArrayFilters(query) {
|
1874 | try {
|
1875 | castArrayFilters(query);
|
1876 | } catch (err) {
|
1877 | query.error(err);
|
1878 | }
|
1879 | }
|
1880 |
|
1881 | /**
|
1882 | * Thunk around find()
|
1883 | *
|
1884 | * @param {Function} [callback]
|
1885 | * @return {Query} this
|
1886 | * @api private
|
1887 | */
|
1888 | Query.prototype._find = wrapThunk(function(callback) {
|
1889 | this._castConditions();
|
1890 |
|
1891 | if (this.error() != null) {
|
1892 | callback(this.error());
|
1893 | return null;
|
1894 | }
|
1895 |
|
1896 | callback = _wrapThunkCallback(this, callback);
|
1897 |
|
1898 | this._applyPaths();
|
1899 | this._fields = this._castFields(this._fields);
|
1900 |
|
1901 | const fields = this._fieldsForExec();
|
1902 | const mongooseOptions = this._mongooseOptions;
|
1903 | const _this = this;
|
1904 | const userProvidedFields = _this._userProvidedFields || {};
|
1905 |
|
1906 | applyGlobalMaxTimeMS(this.options, this.model);
|
1907 |
|
1908 | // Separate options to pass down to `completeMany()` in case we need to
|
1909 | // set a session on the document
|
1910 | const completeManyOptions = Object.assign({}, {
|
1911 | session: get(this, 'options.session', null)
|
1912 | });
|
1913 |
|
1914 | const cb = (err, docs) => {
|
1915 | if (err) {
|
1916 | return callback(err);
|
1917 | }
|
1918 |
|
1919 | if (docs.length === 0) {
|
1920 | return callback(null, docs);
|
1921 | }
|
1922 | if (this.options.explain) {
|
1923 | return callback(null, docs);
|
1924 | }
|
1925 |
|
1926 | if (!mongooseOptions.populate) {
|
1927 | return mongooseOptions.lean ?
|
1928 | callback(null, docs) :
|
1929 | completeMany(_this.model, docs, fields, userProvidedFields, completeManyOptions, callback);
|
1930 | }
|
1931 |
|
1932 | const pop = helpers.preparePopulationOptionsMQ(_this, mongooseOptions);
|
1933 | completeManyOptions.populated = pop;
|
1934 | _this.model.populate(docs, pop, function(err, docs) {
|
1935 | if (err) return callback(err);
|
1936 | return mongooseOptions.lean ?
|
1937 | callback(null, docs) :
|
1938 | completeMany(_this.model, docs, fields, userProvidedFields, completeManyOptions, callback);
|
1939 | });
|
1940 | };
|
1941 |
|
1942 | const options = this._optionsForExec();
|
1943 | options.projection = this._fieldsForExec();
|
1944 | const filter = this._conditions;
|
1945 |
|
1946 | this._collection.find(filter, options, cb);
|
1947 | return null;
|
1948 | });
|
1949 |
|
1950 | /**
|
1951 | * Find all documents that match `selector`. The result will be an array of documents.
|
1952 | *
|
1953 | * If there are too many documents in the result to fit in memory, use
|
1954 | * [`Query.prototype.cursor()`](api.html#query_Query-cursor)
|
1955 | *
|
1956 | * ####Example
|
1957 | *
|
1958 | * // Using async/await
|
1959 | * const arr = await Movie.find({ year: { $gte: 1980, $lte: 1989 } });
|
1960 | *
|
1961 | * // Using callbacks
|
1962 | * Movie.find({ year: { $gte: 1980, $lte: 1989 } }, function(err, arr) {});
|
1963 | *
|
1964 | * @param {Object|ObjectId} [filter] mongodb selector. If not specified, returns all documents.
|
1965 | * @param {Function} [callback]
|
1966 | * @return {Query} this
|
1967 | * @api public
|
1968 | */
|
1969 |
|
1970 | Query.prototype.find = function(conditions, callback) {
|
1971 | if (typeof conditions === 'function') {
|
1972 | callback = conditions;
|
1973 | conditions = {};
|
1974 | }
|
1975 |
|
1976 | conditions = utils.toObject(conditions);
|
1977 |
|
1978 | if (mquery.canMerge(conditions)) {
|
1979 | this.merge(conditions);
|
1980 |
|
1981 | prepareDiscriminatorCriteria(this);
|
1982 | } else if (conditions != null) {
|
1983 | this.error(new ObjectParameterError(conditions, 'filter', 'find'));
|
1984 | }
|
1985 |
|
1986 | // if we don't have a callback, then just return the query object
|
1987 | if (!callback) {
|
1988 | return Query.base.find.call(this);
|
1989 | }
|
1990 |
|
1991 | this._find(callback);
|
1992 |
|
1993 | return this;
|
1994 | };
|
1995 |
|
1996 | /**
|
1997 | * Merges another Query or conditions object into this one.
|
1998 | *
|
1999 | * When a Query is passed, conditions, field selection and options are merged.
|
2000 | *
|
2001 | * @param {Query|Object} source
|
2002 | * @return {Query} this
|
2003 | */
|
2004 |
|
2005 | Query.prototype.merge = function(source) {
|
2006 | if (!source) {
|
2007 | return this;
|
2008 | }
|
2009 |
|
2010 | const opts = { overwrite: true };
|
2011 |
|
2012 | if (source instanceof Query) {
|
2013 | // if source has a feature, apply it to ourselves
|
2014 |
|
2015 | if (source._conditions) {
|
2016 | utils.merge(this._conditions, source._conditions, opts);
|
2017 | }
|
2018 |
|
2019 | if (source._fields) {
|
2020 | this._fields || (this._fields = {});
|
2021 | utils.merge(this._fields, source._fields, opts);
|
2022 | }
|
2023 |
|
2024 | if (source.options) {
|
2025 | this.options || (this.options = {});
|
2026 | utils.merge(this.options, source.options, opts);
|
2027 | }
|
2028 |
|
2029 | if (source._update) {
|
2030 | this._update || (this._update = {});
|
2031 | utils.mergeClone(this._update, source._update);
|
2032 | }
|
2033 |
|
2034 | if (source._distinct) {
|
2035 | this._distinct = source._distinct;
|
2036 | }
|
2037 |
|
2038 | utils.merge(this._mongooseOptions, source._mongooseOptions);
|
2039 |
|
2040 | return this;
|
2041 | }
|
2042 |
|
2043 | // plain object
|
2044 | utils.merge(this._conditions, source, opts);
|
2045 |
|
2046 | return this;
|
2047 | };
|
2048 |
|
2049 | /**
|
2050 | * Adds a collation to this op (MongoDB 3.4 and up)
|
2051 | *
|
2052 | * @param {Object} value
|
2053 | * @return {Query} this
|
2054 | * @see MongoDB docs https://docs.mongodb.com/manual/reference/method/cursor.collation/#cursor.collation
|
2055 | * @api public
|
2056 | */
|
2057 |
|
2058 | Query.prototype.collation = function(value) {
|
2059 | if (this.options == null) {
|
2060 | this.options = {};
|
2061 | }
|
2062 | this.options.collation = value;
|
2063 | return this;
|
2064 | };
|
2065 |
|
2066 | /**
|
2067 | * Hydrate a single doc from `findOne()`, `findOneAndUpdate()`, etc.
|
2068 | *
|
2069 | * @api private
|
2070 | */
|
2071 |
|
2072 | Query.prototype._completeOne = function(doc, res, callback) {
|
2073 | if (!doc && !this.options.rawResult) {
|
2074 | return callback(null, null);
|
2075 | }
|
2076 |
|
2077 | const model = this.model;
|
2078 | const projection = utils.clone(this._fields);
|
2079 | const userProvidedFields = this._userProvidedFields || {};
|
2080 | // `populate`, `lean`
|
2081 | const mongooseOptions = this._mongooseOptions;
|
2082 | // `rawResult`
|
2083 | const options = this.options;
|
2084 |
|
2085 | if (options.explain) {
|
2086 | return callback(null, doc);
|
2087 | }
|
2088 |
|
2089 | if (!mongooseOptions.populate) {
|
2090 | return mongooseOptions.lean ?
|
2091 | _completeOneLean(doc, res, options, callback) :
|
2092 | completeOne(model, doc, res, options, projection, userProvidedFields,
|
2093 | null, callback);
|
2094 | }
|
2095 |
|
2096 | const pop = helpers.preparePopulationOptionsMQ(this, this._mongooseOptions);
|
2097 | model.populate(doc, pop, (err, doc) => {
|
2098 | if (err) {
|
2099 | return callback(err);
|
2100 | }
|
2101 | return mongooseOptions.lean ?
|
2102 | _completeOneLean(doc, res, options, callback) :
|
2103 | completeOne(model, doc, res, options, projection, userProvidedFields,
|
2104 | pop, callback);
|
2105 | });
|
2106 | };
|
2107 |
|
2108 | /**
|
2109 | * Thunk around findOne()
|
2110 | *
|
2111 | * @param {Function} [callback]
|
2112 | * @see findOne http://docs.mongodb.org/manual/reference/method/db.collection.findOne/
|
2113 | * @api private
|
2114 | */
|
2115 |
|
2116 | Query.prototype._findOne = wrapThunk(function(callback) {
|
2117 | this._castConditions();
|
2118 |
|
2119 | if (this.error()) {
|
2120 | callback(this.error());
|
2121 | return null;
|
2122 | }
|
2123 |
|
2124 | this._applyPaths();
|
2125 | this._fields = this._castFields(this._fields);
|
2126 |
|
2127 | applyGlobalMaxTimeMS(this.options, this.model);
|
2128 |
|
2129 | // don't pass in the conditions because we already merged them in
|
2130 | Query.base.findOne.call(this, {}, (err, doc) => {
|
2131 | if (err) {
|
2132 | callback(err);
|
2133 | return null;
|
2134 | }
|
2135 |
|
2136 | this._completeOne(doc, null, _wrapThunkCallback(this, callback));
|
2137 | });
|
2138 | });
|
2139 |
|
2140 | /**
|
2141 | * Declares the query a findOne operation. When executed, the first found document is passed to the callback.
|
2142 | *
|
2143 | * Passing a `callback` executes the query. The result of the query is a single document.
|
2144 | *
|
2145 | * * *Note:* `conditions` is optional, and if `conditions` is null or undefined,
|
2146 | * mongoose will send an empty `findOne` command to MongoDB, which will return
|
2147 | * an arbitrary document. If you're querying by `_id`, use `Model.findById()`
|
2148 | * instead.
|
2149 | *
|
2150 | * This function triggers the following middleware.
|
2151 | *
|
2152 | * - `findOne()`
|
2153 | *
|
2154 | * ####Example
|
2155 | *
|
2156 | * var query = Kitten.where({ color: 'white' });
|
2157 | * query.findOne(function (err, kitten) {
|
2158 | * if (err) return handleError(err);
|
2159 | * if (kitten) {
|
2160 | * // doc may be null if no document matched
|
2161 | * }
|
2162 | * });
|
2163 | *
|
2164 | * @param {Object} [filter] mongodb selector
|
2165 | * @param {Object} [projection] optional fields to return
|
2166 | * @param {Object} [options] see [`setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions)
|
2167 | * @param {Function} [callback] optional params are (error, document)
|
2168 | * @return {Query} this
|
2169 | * @see findOne http://docs.mongodb.org/manual/reference/method/db.collection.findOne/
|
2170 | * @see Query.select #query_Query-select
|
2171 | * @api public
|
2172 | */
|
2173 |
|
2174 | Query.prototype.findOne = function(conditions, projection, options, callback) {
|
2175 | if (typeof conditions === 'function') {
|
2176 | callback = conditions;
|
2177 | conditions = null;
|
2178 | projection = null;
|
2179 | options = null;
|
2180 | } else if (typeof projection === 'function') {
|
2181 | callback = projection;
|
2182 | options = null;
|
2183 | projection = null;
|
2184 | } else if (typeof options === 'function') {
|
2185 | callback = options;
|
2186 | options = null;
|
2187 | }
|
2188 |
|
2189 | // make sure we don't send in the whole Document to merge()
|
2190 | conditions = utils.toObject(conditions);
|
2191 |
|
2192 | this.op = 'findOne';
|
2193 |
|
2194 | if (options) {
|
2195 | this.setOptions(options);
|
2196 | }
|
2197 |
|
2198 | if (projection) {
|
2199 | this.select(projection);
|
2200 | }
|
2201 |
|
2202 | if (mquery.canMerge(conditions)) {
|
2203 | this.merge(conditions);
|
2204 |
|
2205 | prepareDiscriminatorCriteria(this);
|
2206 | } else if (conditions != null) {
|
2207 | this.error(new ObjectParameterError(conditions, 'filter', 'findOne'));
|
2208 | }
|
2209 |
|
2210 | if (!callback) {
|
2211 | // already merged in the conditions, don't need to send them in.
|
2212 | return Query.base.findOne.call(this);
|
2213 | }
|
2214 |
|
2215 | this._findOne(callback);
|
2216 |
|
2217 | return this;
|
2218 | };
|
2219 |
|
2220 | /**
|
2221 | * Thunk around count()
|
2222 | *
|
2223 | * @param {Function} [callback]
|
2224 | * @see count http://docs.mongodb.org/manual/reference/method/db.collection.count/
|
2225 | * @api private
|
2226 | */
|
2227 |
|
2228 | Query.prototype._count = wrapThunk(function(callback) {
|
2229 | try {
|
2230 | this.cast(this.model);
|
2231 | } catch (err) {
|
2232 | this.error(err);
|
2233 | }
|
2234 |
|
2235 | if (this.error()) {
|
2236 | return callback(this.error());
|
2237 | }
|
2238 |
|
2239 | const conds = this._conditions;
|
2240 | const options = this._optionsForExec();
|
2241 |
|
2242 | this._collection.count(conds, options, utils.tick(callback));
|
2243 | });
|
2244 |
|
2245 | /**
|
2246 | * Thunk around countDocuments()
|
2247 | *
|
2248 | * @param {Function} [callback]
|
2249 | * @see countDocuments http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#countDocuments
|
2250 | * @api private
|
2251 | */
|
2252 |
|
2253 | Query.prototype._countDocuments = wrapThunk(function(callback) {
|
2254 | try {
|
2255 | this.cast(this.model);
|
2256 | } catch (err) {
|
2257 | this.error(err);
|
2258 | }
|
2259 |
|
2260 | if (this.error()) {
|
2261 | return callback(this.error());
|
2262 | }
|
2263 |
|
2264 | const conds = this._conditions;
|
2265 | const options = this._optionsForExec();
|
2266 |
|
2267 | this._collection.collection.countDocuments(conds, options, utils.tick(callback));
|
2268 | });
|
2269 |
|
2270 | /**
|
2271 | * Thunk around estimatedDocumentCount()
|
2272 | *
|
2273 | * @param {Function} [callback]
|
2274 | * @see estimatedDocumentCount http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#estimatedDocumentCount
|
2275 | * @api private
|
2276 | */
|
2277 |
|
2278 | Query.prototype._estimatedDocumentCount = wrapThunk(function(callback) {
|
2279 | if (this.error()) {
|
2280 | return callback(this.error());
|
2281 | }
|
2282 |
|
2283 | const options = this._optionsForExec();
|
2284 |
|
2285 | this._collection.collection.estimatedDocumentCount(options, utils.tick(callback));
|
2286 | });
|
2287 |
|
2288 | /**
|
2289 | * Specifies this query as a `count` query.
|
2290 | *
|
2291 | * This method is deprecated. If you want to count the number of documents in
|
2292 | * a collection, e.g. `count({})`, use the [`estimatedDocumentCount()` function](/docs/api.html#query_Query-estimatedDocumentCount)
|
2293 | * instead. Otherwise, use the [`countDocuments()`](/docs/api.html#query_Query-countDocuments) function instead.
|
2294 | *
|
2295 | * Passing a `callback` executes the query.
|
2296 | *
|
2297 | * This function triggers the following middleware.
|
2298 | *
|
2299 | * - `count()`
|
2300 | *
|
2301 | * ####Example:
|
2302 | *
|
2303 | * var countQuery = model.where({ 'color': 'black' }).count();
|
2304 | *
|
2305 | * query.count({ color: 'black' }).count(callback)
|
2306 | *
|
2307 | * query.count({ color: 'black' }, callback)
|
2308 | *
|
2309 | * query.where('color', 'black').count(function (err, count) {
|
2310 | * if (err) return handleError(err);
|
2311 | * console.log('there are %d kittens', count);
|
2312 | * })
|
2313 | *
|
2314 | * @deprecated
|
2315 | * @param {Object} [filter] count documents that match this object
|
2316 | * @param {Function} [callback] optional params are (error, count)
|
2317 | * @return {Query} this
|
2318 | * @see count http://docs.mongodb.org/manual/reference/method/db.collection.count/
|
2319 | * @api public
|
2320 | */
|
2321 |
|
2322 | Query.prototype.count = function(filter, callback) {
|
2323 | if (typeof filter === 'function') {
|
2324 | callback = filter;
|
2325 | filter = undefined;
|
2326 | }
|
2327 |
|
2328 | filter = utils.toObject(filter);
|
2329 |
|
2330 | if (mquery.canMerge(filter)) {
|
2331 | this.merge(filter);
|
2332 | }
|
2333 |
|
2334 | this.op = 'count';
|
2335 | if (!callback) {
|
2336 | return this;
|
2337 | }
|
2338 |
|
2339 | this._count(callback);
|
2340 |
|
2341 | return this;
|
2342 | };
|
2343 |
|
2344 | /**
|
2345 | * Specifies this query as a `estimatedDocumentCount()` query. Faster than
|
2346 | * using `countDocuments()` for large collections because
|
2347 | * `estimatedDocumentCount()` uses collection metadata rather than scanning
|
2348 | * the entire collection.
|
2349 | *
|
2350 | * `estimatedDocumentCount()` does **not** accept a filter. `Model.find({ foo: bar }).estimatedDocumentCount()`
|
2351 | * is equivalent to `Model.find().estimatedDocumentCount()`
|
2352 | *
|
2353 | * This function triggers the following middleware.
|
2354 | *
|
2355 | * - `estimatedDocumentCount()`
|
2356 | *
|
2357 | * ####Example:
|
2358 | *
|
2359 | * await Model.find().estimatedDocumentCount();
|
2360 | *
|
2361 | * @param {Object} [options] passed transparently to the [MongoDB driver](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#estimatedDocumentCount)
|
2362 | * @param {Function} [callback] optional params are (error, count)
|
2363 | * @return {Query} this
|
2364 | * @see estimatedDocumentCount http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#estimatedDocumentCount
|
2365 | * @api public
|
2366 | */
|
2367 |
|
2368 | Query.prototype.estimatedDocumentCount = function(options, callback) {
|
2369 | if (typeof options === 'function') {
|
2370 | callback = options;
|
2371 | options = undefined;
|
2372 | }
|
2373 |
|
2374 | if (typeof options === 'object' && options != null) {
|
2375 | this.setOptions(options);
|
2376 | }
|
2377 |
|
2378 | this.op = 'estimatedDocumentCount';
|
2379 | if (!callback) {
|
2380 | return this;
|
2381 | }
|
2382 |
|
2383 | this._estimatedDocumentCount(callback);
|
2384 |
|
2385 | return this;
|
2386 | };
|
2387 |
|
2388 | /**
|
2389 | * Specifies this query as a `countDocuments()` query. Behaves like `count()`,
|
2390 | * except it always does a full collection scan when passed an empty filter `{}`.
|
2391 | *
|
2392 | * There are also minor differences in how `countDocuments()` handles
|
2393 | * [`$where` and a couple geospatial operators](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#countDocuments).
|
2394 | * versus `count()`.
|
2395 | *
|
2396 | * Passing a `callback` executes the query.
|
2397 | *
|
2398 | * This function triggers the following middleware.
|
2399 | *
|
2400 | * - `countDocuments()`
|
2401 | *
|
2402 | * ####Example:
|
2403 | *
|
2404 | * const countQuery = model.where({ 'color': 'black' }).countDocuments();
|
2405 | *
|
2406 | * query.countDocuments({ color: 'black' }).count(callback);
|
2407 | *
|
2408 | * query.countDocuments({ color: 'black' }, callback);
|
2409 | *
|
2410 | * query.where('color', 'black').countDocuments(function(err, count) {
|
2411 | * if (err) return handleError(err);
|
2412 | * console.log('there are %d kittens', count);
|
2413 | * });
|
2414 | *
|
2415 | * The `countDocuments()` function is similar to `count()`, but there are a
|
2416 | * [few operators that `countDocuments()` does not support](https://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#countDocuments).
|
2417 | * Below are the operators that `count()` supports but `countDocuments()` does not,
|
2418 | * and the suggested replacement:
|
2419 | *
|
2420 | * - `$where`: [`$expr`](https://docs.mongodb.com/manual/reference/operator/query/expr/)
|
2421 | * - `$near`: [`$geoWithin`](https://docs.mongodb.com/manual/reference/operator/query/geoWithin/) with [`$center`](https://docs.mongodb.com/manual/reference/operator/query/center/#op._S_center)
|
2422 | * - `$nearSphere`: [`$geoWithin`](https://docs.mongodb.com/manual/reference/operator/query/geoWithin/) with [`$centerSphere`](https://docs.mongodb.com/manual/reference/operator/query/centerSphere/#op._S_centerSphere)
|
2423 | *
|
2424 | * @param {Object} [filter] mongodb selector
|
2425 | * @param {Function} [callback] optional params are (error, count)
|
2426 | * @return {Query} this
|
2427 | * @see countDocuments http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#countDocuments
|
2428 | * @api public
|
2429 | */
|
2430 |
|
2431 | Query.prototype.countDocuments = function(conditions, callback) {
|
2432 | if (typeof conditions === 'function') {
|
2433 | callback = conditions;
|
2434 | conditions = undefined;
|
2435 | }
|
2436 |
|
2437 | conditions = utils.toObject(conditions);
|
2438 |
|
2439 | if (mquery.canMerge(conditions)) {
|
2440 | this.merge(conditions);
|
2441 | }
|
2442 |
|
2443 | this.op = 'countDocuments';
|
2444 | if (!callback) {
|
2445 | return this;
|
2446 | }
|
2447 |
|
2448 | this._countDocuments(callback);
|
2449 |
|
2450 | return this;
|
2451 | };
|
2452 |
|
2453 | /**
|
2454 | * Thunk around findOne()
|
2455 | *
|
2456 | * @param {Function} [callback]
|
2457 | * @see findOne http://docs.mongodb.org/manual/reference/method/db.collection.findOne/
|
2458 | * @api private
|
2459 | */
|
2460 |
|
2461 | Query.prototype.__distinct = wrapThunk(function __distinct(callback) {
|
2462 | this._castConditions();
|
2463 |
|
2464 | if (this.error()) {
|
2465 | callback(this.error());
|
2466 | return null;
|
2467 | }
|
2468 |
|
2469 | // don't pass in the conditions because we already merged them in
|
2470 | this._collection.collection.
|
2471 | distinct(this._distinct, this._conditions, callback);
|
2472 | });
|
2473 |
|
2474 | /**
|
2475 | * Declares or executes a distinct() operation.
|
2476 | *
|
2477 | * Passing a `callback` executes the query.
|
2478 | *
|
2479 | * This function does not trigger any middleware.
|
2480 | *
|
2481 | * ####Example
|
2482 | *
|
2483 | * distinct(field, conditions, callback)
|
2484 | * distinct(field, conditions)
|
2485 | * distinct(field, callback)
|
2486 | * distinct(field)
|
2487 | * distinct(callback)
|
2488 | * distinct()
|
2489 | *
|
2490 | * @param {String} [field]
|
2491 | * @param {Object|Query} [filter]
|
2492 | * @param {Function} [callback] optional params are (error, arr)
|
2493 | * @return {Query} this
|
2494 | * @see distinct http://docs.mongodb.org/manual/reference/method/db.collection.distinct/
|
2495 | * @api public
|
2496 | */
|
2497 |
|
2498 | Query.prototype.distinct = function(field, conditions, callback) {
|
2499 | if (!callback) {
|
2500 | if (typeof conditions === 'function') {
|
2501 | callback = conditions;
|
2502 | conditions = undefined;
|
2503 | } else if (typeof field === 'function') {
|
2504 | callback = field;
|
2505 | field = undefined;
|
2506 | conditions = undefined;
|
2507 | }
|
2508 | }
|
2509 |
|
2510 | conditions = utils.toObject(conditions);
|
2511 |
|
2512 | if (mquery.canMerge(conditions)) {
|
2513 | this.merge(conditions);
|
2514 |
|
2515 | prepareDiscriminatorCriteria(this);
|
2516 | } else if (conditions != null) {
|
2517 | this.error(new ObjectParameterError(conditions, 'filter', 'distinct'));
|
2518 | }
|
2519 |
|
2520 | if (field != null) {
|
2521 | this._distinct = field;
|
2522 | }
|
2523 | this.op = 'distinct';
|
2524 |
|
2525 | if (callback != null) {
|
2526 | this.__distinct(callback);
|
2527 | }
|
2528 |
|
2529 | return this;
|
2530 | };
|
2531 |
|
2532 | /**
|
2533 | * Sets the sort order
|
2534 | *
|
2535 | * If an object is passed, values allowed are `asc`, `desc`, `ascending`, `descending`, `1`, and `-1`.
|
2536 | *
|
2537 | * If a string is passed, it must be a space delimited list of path names. The
|
2538 | * sort order of each path is ascending unless the path name is prefixed with `-`
|
2539 | * which will be treated as descending.
|
2540 | *
|
2541 | * ####Example
|
2542 | *
|
2543 | * // sort by "field" ascending and "test" descending
|
2544 | * query.sort({ field: 'asc', test: -1 });
|
2545 | *
|
2546 | * // equivalent
|
2547 | * query.sort('field -test');
|
2548 | *
|
2549 | * ####Note
|
2550 | *
|
2551 | * Cannot be used with `distinct()`
|
2552 | *
|
2553 | * @param {Object|String} arg
|
2554 | * @return {Query} this
|
2555 | * @see cursor.sort http://docs.mongodb.org/manual/reference/method/cursor.sort/
|
2556 | * @api public
|
2557 | */
|
2558 |
|
2559 | Query.prototype.sort = function(arg) {
|
2560 | if (arguments.length > 1) {
|
2561 | throw new Error('sort() only takes 1 Argument');
|
2562 | }
|
2563 |
|
2564 | return Query.base.sort.call(this, arg);
|
2565 | };
|
2566 |
|
2567 | /**
|
2568 | * Declare and/or execute this query as a remove() operation. `remove()` is
|
2569 | * deprecated, you should use [`deleteOne()`](#query_Query-deleteOne)
|
2570 | * or [`deleteMany()`](#query_Query-deleteMany) instead.
|
2571 | *
|
2572 | * This function does not trigger any middleware
|
2573 | *
|
2574 | * ####Example
|
2575 | *
|
2576 | * Character.remove({ name: /Stark/ }, callback);
|
2577 | *
|
2578 | * This function calls the MongoDB driver's [`Collection#remove()` function](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#remove).
|
2579 | * The returned [promise](https://mongoosejs.com/docs/queries.html) resolves to an
|
2580 | * object that contains 3 properties:
|
2581 | *
|
2582 | * - `ok`: `1` if no errors occurred
|
2583 | * - `deletedCount`: the number of documents deleted
|
2584 | * - `n`: the number of documents deleted. Equal to `deletedCount`.
|
2585 | *
|
2586 | * ####Example
|
2587 | *
|
2588 | * const res = await Character.remove({ name: /Stark/ });
|
2589 | * // Number of docs deleted
|
2590 | * res.deletedCount;
|
2591 | *
|
2592 | * ####Note
|
2593 | *
|
2594 | * Calling `remove()` creates a [Mongoose query](./queries.html), and a query
|
2595 | * does not execute until you either pass a callback, call [`Query#then()`](#query_Query-then),
|
2596 | * or call [`Query#exec()`](#query_Query-exec).
|
2597 | *
|
2598 | * // not executed
|
2599 | * const query = Character.remove({ name: /Stark/ });
|
2600 | *
|
2601 | * // executed
|
2602 | * Character.remove({ name: /Stark/ }, callback);
|
2603 | * Character.remove({ name: /Stark/ }).remove(callback);
|
2604 | *
|
2605 | * // executed without a callback
|
2606 | * Character.exec();
|
2607 | *
|
2608 | * @param {Object|Query} [filter] mongodb selector
|
2609 | * @param {Function} [callback] optional params are (error, mongooseDeleteResult)
|
2610 | * @return {Query} this
|
2611 | * @deprecated
|
2612 | * @see deleteWriteOpResult http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#~deleteWriteOpResult
|
2613 | * @see MongoDB driver remove http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#remove
|
2614 | * @api public
|
2615 | */
|
2616 |
|
2617 | Query.prototype.remove = function(filter, callback) {
|
2618 | if (typeof filter === 'function') {
|
2619 | callback = filter;
|
2620 | filter = null;
|
2621 | }
|
2622 |
|
2623 | filter = utils.toObject(filter);
|
2624 |
|
2625 | if (mquery.canMerge(filter)) {
|
2626 | this.merge(filter);
|
2627 |
|
2628 | prepareDiscriminatorCriteria(this);
|
2629 | } else if (filter != null) {
|
2630 | this.error(new ObjectParameterError(filter, 'filter', 'remove'));
|
2631 | }
|
2632 |
|
2633 | if (!callback) {
|
2634 | return Query.base.remove.call(this);
|
2635 | }
|
2636 |
|
2637 | this._remove(callback);
|
2638 | return this;
|
2639 | };
|
2640 |
|
2641 | /*!
|
2642 | * ignore
|
2643 | */
|
2644 |
|
2645 | Query.prototype._remove = wrapThunk(function(callback) {
|
2646 | this._castConditions();
|
2647 |
|
2648 | if (this.error() != null) {
|
2649 | callback(this.error());
|
2650 | return this;
|
2651 | }
|
2652 |
|
2653 | callback = _wrapThunkCallback(this, callback);
|
2654 |
|
2655 | return Query.base.remove.call(this, helpers.handleDeleteWriteOpResult(callback));
|
2656 | });
|
2657 |
|
2658 | /**
|
2659 | * Declare and/or execute this query as a `deleteOne()` operation. Works like
|
2660 | * remove, except it deletes at most one document regardless of the `single`
|
2661 | * option.
|
2662 | *
|
2663 | * This function does not trigger any middleware.
|
2664 | *
|
2665 | * ####Example
|
2666 | *
|
2667 | * Character.deleteOne({ name: 'Eddard Stark' }, callback);
|
2668 | * Character.deleteOne({ name: 'Eddard Stark' }).then(next);
|
2669 | *
|
2670 | * This function calls the MongoDB driver's [`Collection#deleteOne()` function](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#deleteOne).
|
2671 | * The returned [promise](https://mongoosejs.com/docs/queries.html) resolves to an
|
2672 | * object that contains 3 properties:
|
2673 | *
|
2674 | * - `ok`: `1` if no errors occurred
|
2675 | * - `deletedCount`: the number of documents deleted
|
2676 | * - `n`: the number of documents deleted. Equal to `deletedCount`.
|
2677 | *
|
2678 | * ####Example
|
2679 | *
|
2680 | * const res = await Character.deleteOne({ name: 'Eddard Stark' });
|
2681 | * // `1` if MongoDB deleted a doc, `0` if no docs matched the filter `{ name: ... }`
|
2682 | * res.deletedCount;
|
2683 | *
|
2684 | * @param {Object|Query} [filter] mongodb selector
|
2685 | * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions)
|
2686 | * @param {Function} [callback] optional params are (error, mongooseDeleteResult)
|
2687 | * @return {Query} this
|
2688 | * @see deleteWriteOpResult http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#~deleteWriteOpResult
|
2689 | * @see MongoDB Driver deleteOne http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#deleteOne
|
2690 | * @api public
|
2691 | */
|
2692 |
|
2693 | Query.prototype.deleteOne = function(filter, options, callback) {
|
2694 | if (typeof filter === 'function') {
|
2695 | callback = filter;
|
2696 | filter = null;
|
2697 | options = null;
|
2698 | } else if (typeof options === 'function') {
|
2699 | callback = options;
|
2700 | options = null;
|
2701 | } else {
|
2702 | this.setOptions(options);
|
2703 | }
|
2704 |
|
2705 | filter = utils.toObject(filter);
|
2706 |
|
2707 | if (mquery.canMerge(filter)) {
|
2708 | this.merge(filter);
|
2709 |
|
2710 | prepareDiscriminatorCriteria(this);
|
2711 | } else if (filter != null) {
|
2712 | this.error(new ObjectParameterError(filter, 'filter', 'deleteOne'));
|
2713 | }
|
2714 |
|
2715 | if (!callback) {
|
2716 | return Query.base.deleteOne.call(this);
|
2717 | }
|
2718 |
|
2719 | this._deleteOne.call(this, callback);
|
2720 |
|
2721 | return this;
|
2722 | };
|
2723 |
|
2724 | /*!
|
2725 | * Internal thunk for `deleteOne()`
|
2726 | */
|
2727 |
|
2728 | Query.prototype._deleteOne = wrapThunk(function(callback) {
|
2729 | this._castConditions();
|
2730 |
|
2731 | if (this.error() != null) {
|
2732 | callback(this.error());
|
2733 | return this;
|
2734 | }
|
2735 |
|
2736 | callback = _wrapThunkCallback(this, callback);
|
2737 |
|
2738 | return Query.base.deleteOne.call(this, helpers.handleDeleteWriteOpResult(callback));
|
2739 | });
|
2740 |
|
2741 | /**
|
2742 | * Declare and/or execute this query as a `deleteMany()` operation. Works like
|
2743 | * remove, except it deletes _every_ document that matches `filter` in the
|
2744 | * collection, regardless of the value of `single`.
|
2745 | *
|
2746 | * This function does not trigger any middleware
|
2747 | *
|
2748 | * ####Example
|
2749 | *
|
2750 | * Character.deleteMany({ name: /Stark/, age: { $gte: 18 } }, callback)
|
2751 | * Character.deleteMany({ name: /Stark/, age: { $gte: 18 } }).then(next)
|
2752 | *
|
2753 | * This function calls the MongoDB driver's [`Collection#deleteMany()` function](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#deleteMany).
|
2754 | * The returned [promise](https://mongoosejs.com/docs/queries.html) resolves to an
|
2755 | * object that contains 3 properties:
|
2756 | *
|
2757 | * - `ok`: `1` if no errors occurred
|
2758 | * - `deletedCount`: the number of documents deleted
|
2759 | * - `n`: the number of documents deleted. Equal to `deletedCount`.
|
2760 | *
|
2761 | * ####Example
|
2762 | *
|
2763 | * const res = await Character.deleteMany({ name: /Stark/, age: { $gte: 18 } });
|
2764 | * // `0` if no docs matched the filter, number of docs deleted otherwise
|
2765 | * res.deletedCount;
|
2766 | *
|
2767 | * @param {Object|Query} [filter] mongodb selector
|
2768 | * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions)
|
2769 | * @param {Function} [callback] optional params are (error, mongooseDeleteResult)
|
2770 | * @return {Query} this
|
2771 | * @see deleteWriteOpResult http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#~deleteWriteOpResult
|
2772 | * @see MongoDB Driver deleteMany http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#deleteMany
|
2773 | * @api public
|
2774 | */
|
2775 |
|
2776 | Query.prototype.deleteMany = function(filter, options, callback) {
|
2777 | if (typeof filter === 'function') {
|
2778 | callback = filter;
|
2779 | filter = null;
|
2780 | options = null;
|
2781 | } else if (typeof options === 'function') {
|
2782 | callback = options;
|
2783 | options = null;
|
2784 | } else {
|
2785 | this.setOptions(options);
|
2786 | }
|
2787 |
|
2788 | filter = utils.toObject(filter);
|
2789 |
|
2790 | if (mquery.canMerge(filter)) {
|
2791 | this.merge(filter);
|
2792 |
|
2793 | prepareDiscriminatorCriteria(this);
|
2794 | } else if (filter != null) {
|
2795 | this.error(new ObjectParameterError(filter, 'filter', 'deleteMany'));
|
2796 | }
|
2797 |
|
2798 | if (!callback) {
|
2799 | return Query.base.deleteMany.call(this);
|
2800 | }
|
2801 |
|
2802 | this._deleteMany.call(this, callback);
|
2803 |
|
2804 | return this;
|
2805 | };
|
2806 |
|
2807 | /*!
|
2808 | * Internal thunk around `deleteMany()`
|
2809 | */
|
2810 |
|
2811 | Query.prototype._deleteMany = wrapThunk(function(callback) {
|
2812 | this._castConditions();
|
2813 |
|
2814 | if (this.error() != null) {
|
2815 | callback(this.error());
|
2816 | return this;
|
2817 | }
|
2818 |
|
2819 | callback = _wrapThunkCallback(this, callback);
|
2820 |
|
2821 | return Query.base.deleteMany.call(this, helpers.handleDeleteWriteOpResult(callback));
|
2822 | });
|
2823 |
|
2824 | /*!
|
2825 | * hydrates a document
|
2826 | *
|
2827 | * @param {Model} model
|
2828 | * @param {Document} doc
|
2829 | * @param {Object} res 3rd parameter to callback
|
2830 | * @param {Object} fields
|
2831 | * @param {Query} self
|
2832 | * @param {Array} [pop] array of paths used in population
|
2833 | * @param {Function} callback
|
2834 | */
|
2835 |
|
2836 | function completeOne(model, doc, res, options, fields, userProvidedFields, pop, callback) {
|
2837 | const opts = pop ?
|
2838 | {populated: pop}
|
2839 | : undefined;
|
2840 |
|
2841 | if (options.rawResult && doc == null) {
|
2842 | _init(null);
|
2843 | return null;
|
2844 | }
|
2845 |
|
2846 | const casted = helpers.createModel(model, doc, fields, userProvidedFields);
|
2847 | try {
|
2848 | casted.init(doc, opts, _init);
|
2849 | } catch (error) {
|
2850 | _init(error);
|
2851 | }
|
2852 |
|
2853 | function _init(err) {
|
2854 | if (err) {
|
2855 | return process.nextTick(() => callback(err));
|
2856 | }
|
2857 |
|
2858 |
|
2859 | if (options.rawResult) {
|
2860 | if (doc && casted) {
|
2861 | casted.$session(options.session);
|
2862 | res.value = casted;
|
2863 | } else {
|
2864 | res.value = null;
|
2865 | }
|
2866 | return process.nextTick(() => callback(null, res));
|
2867 | }
|
2868 | casted.$session(options.session);
|
2869 | process.nextTick(() => callback(null, casted));
|
2870 | }
|
2871 | }
|
2872 |
|
2873 | /*!
|
2874 | * If the model is a discriminator type and not root, then add the key & value to the criteria.
|
2875 | */
|
2876 |
|
2877 | function prepareDiscriminatorCriteria(query) {
|
2878 | if (!query || !query.model || !query.model.schema) {
|
2879 | return;
|
2880 | }
|
2881 |
|
2882 | const schema = query.model.schema;
|
2883 |
|
2884 | if (schema && schema.discriminatorMapping && !schema.discriminatorMapping.isRoot) {
|
2885 | query._conditions[schema.discriminatorMapping.key] = schema.discriminatorMapping.value;
|
2886 | }
|
2887 | }
|
2888 |
|
2889 | /**
|
2890 | * Issues a mongodb [findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) update command.
|
2891 | *
|
2892 | * Finds a matching document, updates it according to the `update` arg, passing any `options`, and returns the found
|
2893 | * document (if any) to the callback. The query executes if
|
2894 | * `callback` is passed.
|
2895 | *
|
2896 | * This function triggers the following middleware.
|
2897 | *
|
2898 | * - `findOneAndUpdate()`
|
2899 | *
|
2900 | * ####Available options
|
2901 | *
|
2902 | * - `new`: bool - if true, return the modified document rather than the original. defaults to false (changed in 4.0)
|
2903 | * - `upsert`: bool - creates the object if it doesn't exist. defaults to false.
|
2904 | * - `fields`: {Object|String} - Field selection. Equivalent to `.select(fields).findOneAndUpdate()`
|
2905 | * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
|
2906 | * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0
|
2907 | * - `runValidators`: if true, runs [update validators](/docs/validation.html#update-validators) on this command. Update validators validate the update operation against the model's schema.
|
2908 | * - `setDefaultsOnInsert`: if this and `upsert` are true, mongoose will apply the [defaults](http://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created. This option only works on MongoDB >= 2.4 because it relies on [MongoDB's `$setOnInsert` operator](https://docs.mongodb.org/v2.4/reference/operator/update/setOnInsert/).
|
2909 | * - `rawResult`: if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify)
|
2910 | * - `context` (string) if set to 'query' and `runValidators` is on, `this` will refer to the query in custom validator functions that update validation runs. Does nothing if `runValidators` is false.
|
2911 | *
|
2912 | * ####Callback Signature
|
2913 | * function(error, doc) {
|
2914 | * // error: any errors that occurred
|
2915 | * // doc: the document before updates are applied if `new: false`, or after updates if `new = true`
|
2916 | * }
|
2917 | *
|
2918 | * ####Examples
|
2919 | *
|
2920 | * query.findOneAndUpdate(conditions, update, options, callback) // executes
|
2921 | * query.findOneAndUpdate(conditions, update, options) // returns Query
|
2922 | * query.findOneAndUpdate(conditions, update, callback) // executes
|
2923 | * query.findOneAndUpdate(conditions, update) // returns Query
|
2924 | * query.findOneAndUpdate(update, callback) // returns Query
|
2925 | * query.findOneAndUpdate(update) // returns Query
|
2926 | * query.findOneAndUpdate(callback) // executes
|
2927 | * query.findOneAndUpdate() // returns Query
|
2928 | *
|
2929 | * @method findOneAndUpdate
|
2930 | * @memberOf Query
|
2931 | * @instance
|
2932 | * @param {Object|Query} [filter]
|
2933 | * @param {Object} [doc]
|
2934 | * @param {Object} [options]
|
2935 | * @param {Boolean} [options.rawResult] if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify)
|
2936 | * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
|
2937 | * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](/docs/transactions.html).
|
2938 | * @param {Boolean} [options.multipleCastError] by default, mongoose only returns the first error that occurred in casting the query. Turn on this option to aggregate all the cast errors.
|
2939 | * @param {Object} [options.lean] if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See [`Query.lean()`](http://mongoosejs.com/docs/api.html#query_Query-lean).
|
2940 | * @param {Boolean} [options.omitUndefined=false] If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server.
|
2941 | * @param {Function} [callback] optional params are (error, doc), _unless_ `rawResult` is used, in which case params are (error, writeOpResult)
|
2942 | * @see Tutorial /docs/tutorials/findoneandupdate.html
|
2943 | * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command
|
2944 | * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult
|
2945 | * @return {Query} this
|
2946 | * @api public
|
2947 | */
|
2948 |
|
2949 | Query.prototype.findOneAndUpdate = function(criteria, doc, options, callback) {
|
2950 | this.op = 'findOneAndUpdate';
|
2951 | this._validate();
|
2952 |
|
2953 | switch (arguments.length) {
|
2954 | case 3:
|
2955 | if (typeof options === 'function') {
|
2956 | callback = options;
|
2957 | options = {};
|
2958 | }
|
2959 | break;
|
2960 | case 2:
|
2961 | if (typeof doc === 'function') {
|
2962 | callback = doc;
|
2963 | doc = criteria;
|
2964 | criteria = undefined;
|
2965 | }
|
2966 | options = undefined;
|
2967 | break;
|
2968 | case 1:
|
2969 | if (typeof criteria === 'function') {
|
2970 | callback = criteria;
|
2971 | criteria = options = doc = undefined;
|
2972 | } else {
|
2973 | doc = criteria;
|
2974 | criteria = options = undefined;
|
2975 | }
|
2976 | }
|
2977 |
|
2978 | if (mquery.canMerge(criteria)) {
|
2979 | this.merge(criteria);
|
2980 | }
|
2981 |
|
2982 | // apply doc
|
2983 | if (doc) {
|
2984 | this._mergeUpdate(doc);
|
2985 | }
|
2986 |
|
2987 | if (options) {
|
2988 | options = utils.clone(options);
|
2989 | if (options.projection) {
|
2990 | this.select(options.projection);
|
2991 | delete options.projection;
|
2992 | }
|
2993 | if (options.fields) {
|
2994 | this.select(options.fields);
|
2995 | delete options.fields;
|
2996 | }
|
2997 |
|
2998 | this.setOptions(options);
|
2999 | }
|
3000 |
|
3001 | if (!callback) {
|
3002 | return this;
|
3003 | }
|
3004 |
|
3005 | this._findOneAndUpdate(callback);
|
3006 |
|
3007 | return this;
|
3008 | };
|
3009 |
|
3010 | /*!
|
3011 | * Thunk around findOneAndUpdate()
|
3012 | *
|
3013 | * @param {Function} [callback]
|
3014 | * @api private
|
3015 | */
|
3016 |
|
3017 | Query.prototype._findOneAndUpdate = wrapThunk(function(callback) {
|
3018 | if (this.error() != null) {
|
3019 | return callback(this.error());
|
3020 | }
|
3021 |
|
3022 | this._findAndModify('update', callback);
|
3023 | });
|
3024 |
|
3025 | /**
|
3026 | * Issues a mongodb [findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) remove command.
|
3027 | *
|
3028 | * Finds a matching document, removes it, passing the found document (if any) to
|
3029 | * the callback. Executes if `callback` is passed.
|
3030 | *
|
3031 | * This function triggers the following middleware.
|
3032 | *
|
3033 | * - `findOneAndRemove()`
|
3034 | *
|
3035 | * ####Available options
|
3036 | *
|
3037 | * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
|
3038 | * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0
|
3039 | * - `rawResult`: if true, resolves to the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify)
|
3040 | *
|
3041 | * ####Callback Signature
|
3042 | * function(error, doc) {
|
3043 | * // error: any errors that occurred
|
3044 | * // doc: the document before updates are applied if `new: false`, or after updates if `new = true`
|
3045 | * }
|
3046 | *
|
3047 | * ####Examples
|
3048 | *
|
3049 | * A.where().findOneAndRemove(conditions, options, callback) // executes
|
3050 | * A.where().findOneAndRemove(conditions, options) // return Query
|
3051 | * A.where().findOneAndRemove(conditions, callback) // executes
|
3052 | * A.where().findOneAndRemove(conditions) // returns Query
|
3053 | * A.where().findOneAndRemove(callback) // executes
|
3054 | * A.where().findOneAndRemove() // returns Query
|
3055 | *
|
3056 | * @method findOneAndRemove
|
3057 | * @memberOf Query
|
3058 | * @instance
|
3059 | * @param {Object} [conditions]
|
3060 | * @param {Object} [options]
|
3061 | * @param {Boolean} [options.rawResult] if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify)
|
3062 | * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](/docs/transactions.html).
|
3063 | * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
|
3064 | * @param {Function} [callback] optional params are (error, document)
|
3065 | * @return {Query} this
|
3066 | * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command
|
3067 | * @api public
|
3068 | */
|
3069 |
|
3070 | Query.prototype.findOneAndRemove = function(conditions, options, callback) {
|
3071 | this.op = 'findOneAndRemove';
|
3072 | this._validate();
|
3073 |
|
3074 | switch (arguments.length) {
|
3075 | case 2:
|
3076 | if (typeof options === 'function') {
|
3077 | callback = options;
|
3078 | options = {};
|
3079 | }
|
3080 | break;
|
3081 | case 1:
|
3082 | if (typeof conditions === 'function') {
|
3083 | callback = conditions;
|
3084 | conditions = undefined;
|
3085 | options = undefined;
|
3086 | }
|
3087 | break;
|
3088 | }
|
3089 |
|
3090 | if (mquery.canMerge(conditions)) {
|
3091 | this.merge(conditions);
|
3092 | }
|
3093 |
|
3094 | options && this.setOptions(options);
|
3095 |
|
3096 | if (!callback) {
|
3097 | return this;
|
3098 | }
|
3099 |
|
3100 | this._findOneAndRemove(callback);
|
3101 |
|
3102 | return this;
|
3103 | };
|
3104 |
|
3105 | /**
|
3106 | * Issues a MongoDB [findOneAndDelete](https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndDelete/) command.
|
3107 | *
|
3108 | * Finds a matching document, removes it, and passes the found document (if any)
|
3109 | * to the callback. Executes if `callback` is passed.
|
3110 | *
|
3111 | * This function triggers the following middleware.
|
3112 | *
|
3113 | * - `findOneAndDelete()`
|
3114 | *
|
3115 | * This function differs slightly from `Model.findOneAndRemove()` in that
|
3116 | * `findOneAndRemove()` becomes a [MongoDB `findAndModify()` command](https://docs.mongodb.com/manual/reference/method/db.collection.findAndModify/),
|
3117 | * as opposed to a `findOneAndDelete()` command. For most mongoose use cases,
|
3118 | * this distinction is purely pedantic. You should use `findOneAndDelete()`
|
3119 | * unless you have a good reason not to.
|
3120 | *
|
3121 | * ####Available options
|
3122 | *
|
3123 | * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
|
3124 | * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0
|
3125 | * - `rawResult`: if true, resolves to the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify)
|
3126 | *
|
3127 | * ####Callback Signature
|
3128 | * function(error, doc) {
|
3129 | * // error: any errors that occurred
|
3130 | * // doc: the document before updates are applied if `new: false`, or after updates if `new = true`
|
3131 | * }
|
3132 | *
|
3133 | * ####Examples
|
3134 | *
|
3135 | * A.where().findOneAndDelete(conditions, options, callback) // executes
|
3136 | * A.where().findOneAndDelete(conditions, options) // return Query
|
3137 | * A.where().findOneAndDelete(conditions, callback) // executes
|
3138 | * A.where().findOneAndDelete(conditions) // returns Query
|
3139 | * A.where().findOneAndDelete(callback) // executes
|
3140 | * A.where().findOneAndDelete() // returns Query
|
3141 | *
|
3142 | * @method findOneAndDelete
|
3143 | * @memberOf Query
|
3144 | * @param {Object} [conditions]
|
3145 | * @param {Object} [options]
|
3146 | * @param {Boolean} [options.rawResult] if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify)
|
3147 | * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](/docs/transactions.html).
|
3148 | * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
|
3149 | * @param {Function} [callback] optional params are (error, document)
|
3150 | * @return {Query} this
|
3151 | * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command
|
3152 | * @api public
|
3153 | */
|
3154 |
|
3155 | Query.prototype.findOneAndDelete = function(conditions, options, callback) {
|
3156 | this.op = 'findOneAndDelete';
|
3157 | this._validate();
|
3158 |
|
3159 | switch (arguments.length) {
|
3160 | case 2:
|
3161 | if (typeof options === 'function') {
|
3162 | callback = options;
|
3163 | options = {};
|
3164 | }
|
3165 | break;
|
3166 | case 1:
|
3167 | if (typeof conditions === 'function') {
|
3168 | callback = conditions;
|
3169 | conditions = undefined;
|
3170 | options = undefined;
|
3171 | }
|
3172 | break;
|
3173 | }
|
3174 |
|
3175 | if (mquery.canMerge(conditions)) {
|
3176 | this.merge(conditions);
|
3177 | }
|
3178 |
|
3179 | options && this.setOptions(options);
|
3180 |
|
3181 | if (!callback) {
|
3182 | return this;
|
3183 | }
|
3184 |
|
3185 | this._findOneAndDelete(callback);
|
3186 |
|
3187 | return this;
|
3188 | };
|
3189 |
|
3190 | /*!
|
3191 | * Thunk around findOneAndDelete()
|
3192 | *
|
3193 | * @param {Function} [callback]
|
3194 | * @return {Query} this
|
3195 | * @api private
|
3196 | */
|
3197 | Query.prototype._findOneAndDelete = wrapThunk(function(callback) {
|
3198 | this._castConditions();
|
3199 |
|
3200 | if (this.error() != null) {
|
3201 | callback(this.error());
|
3202 | return null;
|
3203 | }
|
3204 |
|
3205 | const filter = this._conditions;
|
3206 | const options = this._optionsForExec();
|
3207 | let fields = null;
|
3208 |
|
3209 | if (this._fields != null) {
|
3210 | options.projection = this._castFields(utils.clone(this._fields));
|
3211 | fields = options.projection;
|
3212 | if (fields instanceof Error) {
|
3213 | callback(fields);
|
3214 | return null;
|
3215 | }
|
3216 | }
|
3217 |
|
3218 | this._collection.collection.findOneAndDelete(filter, options, _wrapThunkCallback(this, (err, res) => {
|
3219 | if (err) {
|
3220 | return callback(err);
|
3221 | }
|
3222 |
|
3223 | const doc = res.value;
|
3224 |
|
3225 | return this._completeOne(doc, res, callback);
|
3226 | }));
|
3227 | });
|
3228 |
|
3229 | /**
|
3230 | * Issues a MongoDB [findOneAndReplace](https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndReplace/) command.
|
3231 | *
|
3232 | * Finds a matching document, removes it, and passes the found document (if any)
|
3233 | * to the callback. Executes if `callback` is passed.
|
3234 | *
|
3235 | * This function triggers the following middleware.
|
3236 | *
|
3237 | * - `findOneAndReplace()`
|
3238 | *
|
3239 | * ####Available options
|
3240 | *
|
3241 | * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
|
3242 | * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0
|
3243 | * - `rawResult`: if true, resolves to the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify)
|
3244 | *
|
3245 | * ####Callback Signature
|
3246 | * function(error, doc) {
|
3247 | * // error: any errors that occurred
|
3248 | * // doc: the document before updates are applied if `new: false`, or after updates if `new = true`
|
3249 | * }
|
3250 | *
|
3251 | * ####Examples
|
3252 | *
|
3253 | * A.where().findOneAndReplace(filter, replacement, options, callback); // executes
|
3254 | * A.where().findOneAndReplace(filter, replacement, options); // return Query
|
3255 | * A.where().findOneAndReplace(filter, replacement, callback); // executes
|
3256 | * A.where().findOneAndReplace(filter); // returns Query
|
3257 | * A.where().findOneAndReplace(callback); // executes
|
3258 | * A.where().findOneAndReplace(); // returns Query
|
3259 | *
|
3260 | * @method findOneAndReplace
|
3261 | * @memberOf Query
|
3262 | * @param {Object} [filter]
|
3263 | * @param {Object} [replacement]
|
3264 | * @param {Object} [options]
|
3265 | * @param {Boolean} [options.rawResult] if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify)
|
3266 | * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](/docs/transactions.html).
|
3267 | * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
|
3268 | * @param {Object} [options.lean] if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See [`Query.lean()`](http://mongoosejs.com/docs/api.html#query_Query-lean).
|
3269 | * @param {Boolean} [options.omitUndefined=false] If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server.
|
3270 | * @param {Function} [callback] optional params are (error, document)
|
3271 | * @return {Query} this
|
3272 | * @api public
|
3273 | */
|
3274 |
|
3275 | Query.prototype.findOneAndReplace = function(filter, replacement, options, callback) {
|
3276 | this.op = 'findOneAndReplace';
|
3277 | this._validate();
|
3278 |
|
3279 | switch (arguments.length) {
|
3280 | case 3:
|
3281 | if (typeof options === 'function') {
|
3282 | callback = options;
|
3283 | options = void 0;
|
3284 | }
|
3285 | break;
|
3286 | case 2:
|
3287 | if (typeof replacement === 'function') {
|
3288 | callback = replacement;
|
3289 | replacement = void 0;
|
3290 | }
|
3291 | break;
|
3292 | case 1:
|
3293 | if (typeof filter === 'function') {
|
3294 | callback = filter;
|
3295 | filter = void 0;
|
3296 | replacement = void 0;
|
3297 | options = void 0;
|
3298 | }
|
3299 | break;
|
3300 | }
|
3301 |
|
3302 | if (mquery.canMerge(filter)) {
|
3303 | this.merge(filter);
|
3304 | }
|
3305 |
|
3306 | if (replacement != null) {
|
3307 | if (hasDollarKeys(replacement)) {
|
3308 | throw new Error('The replacement document must not contain atomic operators.');
|
3309 | }
|
3310 | this._mergeUpdate(replacement);
|
3311 | }
|
3312 |
|
3313 | options && this.setOptions(options);
|
3314 |
|
3315 | if (!callback) {
|
3316 | return this;
|
3317 | }
|
3318 |
|
3319 | this._findOneAndReplace(callback);
|
3320 |
|
3321 | return this;
|
3322 | };
|
3323 |
|
3324 | /*!
|
3325 | * Thunk around findOneAndReplace()
|
3326 | *
|
3327 | * @param {Function} [callback]
|
3328 | * @return {Query} this
|
3329 | * @api private
|
3330 | */
|
3331 | Query.prototype._findOneAndReplace = wrapThunk(function(callback) {
|
3332 | this._castConditions();
|
3333 |
|
3334 | if (this.error() != null) {
|
3335 | callback(this.error());
|
3336 | return null;
|
3337 | }
|
3338 |
|
3339 | const filter = this._conditions;
|
3340 | const options = this._optionsForExec();
|
3341 | convertNewToReturnOriginal(options);
|
3342 | let fields = null;
|
3343 |
|
3344 | let castedDoc = new this.model(this._update, null, true);
|
3345 | this._update = castedDoc;
|
3346 |
|
3347 | this._applyPaths();
|
3348 | if (this._fields != null) {
|
3349 | options.projection = this._castFields(utils.clone(this._fields));
|
3350 | fields = options.projection;
|
3351 | if (fields instanceof Error) {
|
3352 | callback(fields);
|
3353 | return null;
|
3354 | }
|
3355 | }
|
3356 |
|
3357 | castedDoc.validate(err => {
|
3358 | if (err != null) {
|
3359 | return callback(err);
|
3360 | }
|
3361 |
|
3362 | if (castedDoc.toBSON) {
|
3363 | castedDoc = castedDoc.toBSON();
|
3364 | }
|
3365 |
|
3366 | this._collection.collection.findOneAndReplace(filter, castedDoc, options, _wrapThunkCallback(this, (err, res) => {
|
3367 | if (err) {
|
3368 | return callback(err);
|
3369 | }
|
3370 |
|
3371 | const doc = res.value;
|
3372 |
|
3373 | return this._completeOne(doc, res, callback);
|
3374 | }));
|
3375 | });
|
3376 | });
|
3377 |
|
3378 | /*!
|
3379 | * Support the `new` option as an alternative to `returnOriginal` for backwards
|
3380 | * compat.
|
3381 | */
|
3382 |
|
3383 | function convertNewToReturnOriginal(options) {
|
3384 | if ('new' in options) {
|
3385 | options.returnOriginal = !options['new'];
|
3386 | delete options['new'];
|
3387 | }
|
3388 | }
|
3389 |
|
3390 | /*!
|
3391 | * Thunk around findOneAndRemove()
|
3392 | *
|
3393 | * @param {Function} [callback]
|
3394 | * @return {Query} this
|
3395 | * @api private
|
3396 | */
|
3397 | Query.prototype._findOneAndRemove = wrapThunk(function(callback) {
|
3398 | if (this.error() != null) {
|
3399 | callback(this.error());
|
3400 | return;
|
3401 | }
|
3402 |
|
3403 | this._findAndModify('remove', callback);
|
3404 | });
|
3405 |
|
3406 | /*!
|
3407 | * Get options from query opts, falling back to the base mongoose object.
|
3408 | */
|
3409 |
|
3410 | function _getOption(query, option, def) {
|
3411 | const opts = query._optionsForExec(query.model);
|
3412 |
|
3413 | if (option in opts) {
|
3414 | return opts[option];
|
3415 | }
|
3416 | if (option in query.model.base.options) {
|
3417 | return query.model.base.options[option];
|
3418 | }
|
3419 | return def;
|
3420 | }
|
3421 |
|
3422 | /*!
|
3423 | * Override mquery.prototype._findAndModify to provide casting etc.
|
3424 | *
|
3425 | * @param {String} type - either "remove" or "update"
|
3426 | * @param {Function} callback
|
3427 | * @api private
|
3428 | */
|
3429 |
|
3430 | Query.prototype._findAndModify = function(type, callback) {
|
3431 | if (typeof callback !== 'function') {
|
3432 | throw new Error('Expected callback in _findAndModify');
|
3433 | }
|
3434 |
|
3435 | const model = this.model;
|
3436 | const schema = model.schema;
|
3437 | const _this = this;
|
3438 | let fields;
|
3439 |
|
3440 | const castedQuery = castQuery(this);
|
3441 | if (castedQuery instanceof Error) {
|
3442 | return callback(castedQuery);
|
3443 | }
|
3444 |
|
3445 | _castArrayFilters(this);
|
3446 |
|
3447 | const opts = this._optionsForExec(model);
|
3448 |
|
3449 | if ('strict' in opts) {
|
3450 | this._mongooseOptions.strict = opts.strict;
|
3451 | }
|
3452 |
|
3453 | const isOverwriting = this.options.overwrite && !hasDollarKeys(this._update);
|
3454 | if (isOverwriting) {
|
3455 | this._update = new this.model(this._update, null, true);
|
3456 | }
|
3457 |
|
3458 | if (type === 'remove') {
|
3459 | opts.remove = true;
|
3460 | } else {
|
3461 | if (!('new' in opts) && !('returnOriginal' in opts)) {
|
3462 | opts.new = false;
|
3463 | }
|
3464 | if (!('upsert' in opts)) {
|
3465 | opts.upsert = false;
|
3466 | }
|
3467 | if (opts.upsert || opts['new']) {
|
3468 | opts.remove = false;
|
3469 | }
|
3470 |
|
3471 | if (!isOverwriting) {
|
3472 | this._update = castDoc(this, opts.overwrite);
|
3473 | this._update = setDefaultsOnInsert(this._conditions, schema, this._update, opts);
|
3474 | if (!this._update) {
|
3475 | if (opts.upsert) {
|
3476 | // still need to do the upsert to empty doc
|
3477 | const doc = utils.clone(castedQuery);
|
3478 | delete doc._id;
|
3479 | this._update = {$set: doc};
|
3480 | } else {
|
3481 | this.findOne(callback);
|
3482 | return this;
|
3483 | }
|
3484 | } else if (this._update instanceof Error) {
|
3485 | return callback(this._update);
|
3486 | } else {
|
3487 | // In order to make MongoDB 2.6 happy (see
|
3488 | // https://jira.mongodb.org/browse/SERVER-12266 and related issues)
|
3489 | // if we have an actual update document but $set is empty, junk the $set.
|
3490 | if (this._update.$set && Object.keys(this._update.$set).length === 0) {
|
3491 | delete this._update.$set;
|
3492 | }
|
3493 | }
|
3494 | }
|
3495 | }
|
3496 |
|
3497 | this._applyPaths();
|
3498 |
|
3499 | const options = this._mongooseOptions;
|
3500 |
|
3501 | if (this._fields) {
|
3502 | fields = utils.clone(this._fields);
|
3503 | opts.projection = this._castFields(fields);
|
3504 | if (opts.projection instanceof Error) {
|
3505 | return callback(opts.projection);
|
3506 | }
|
3507 | }
|
3508 |
|
3509 | if (opts.sort) convertSortToArray(opts);
|
3510 |
|
3511 | const cb = function(err, doc, res) {
|
3512 | if (err) {
|
3513 | return callback(err);
|
3514 | }
|
3515 |
|
3516 | _this._completeOne(doc, res, callback);
|
3517 | };
|
3518 |
|
3519 | let useFindAndModify = true;
|
3520 | const runValidators = _getOption(this, 'runValidators', false);
|
3521 | const base = _this.model && _this.model.base;
|
3522 | const conn = get(model, 'collection.conn', {});
|
3523 | if ('useFindAndModify' in base.options) {
|
3524 | useFindAndModify = base.get('useFindAndModify');
|
3525 | }
|
3526 | if ('useFindAndModify' in conn.config) {
|
3527 | useFindAndModify = conn.config.useFindAndModify;
|
3528 | }
|
3529 | if ('useFindAndModify' in options) {
|
3530 | useFindAndModify = options.useFindAndModify;
|
3531 | }
|
3532 | if (useFindAndModify === false) {
|
3533 | // Bypass mquery
|
3534 | const collection = _this._collection.collection;
|
3535 | convertNewToReturnOriginal(opts);
|
3536 |
|
3537 | if (type === 'remove') {
|
3538 | collection.findOneAndDelete(castedQuery, opts, _wrapThunkCallback(_this, function(error, res) {
|
3539 | return cb(error, res ? res.value : res, res);
|
3540 | }));
|
3541 |
|
3542 | return this;
|
3543 | }
|
3544 |
|
3545 | // honors legacy overwrite option for backward compatibility
|
3546 | const updateMethod = isOverwriting ? 'findOneAndReplace' : 'findOneAndUpdate';
|
3547 |
|
3548 | if (runValidators) {
|
3549 | this.validate(this._update, opts, isOverwriting, error => {
|
3550 | if (error) {
|
3551 | return callback(error);
|
3552 | }
|
3553 | if (this._update && this._update.toBSON) {
|
3554 | this._update = this._update.toBSON();
|
3555 | }
|
3556 |
|
3557 | collection[updateMethod](castedQuery, this._update, opts, _wrapThunkCallback(_this, function(error, res) {
|
3558 | return cb(error, res ? res.value : res, res);
|
3559 | }));
|
3560 | });
|
3561 | } else {
|
3562 | if (this._update && this._update.toBSON) {
|
3563 | this._update = this._update.toBSON();
|
3564 | }
|
3565 | collection[updateMethod](castedQuery, this._update, opts, _wrapThunkCallback(_this, function(error, res) {
|
3566 | return cb(error, res ? res.value : res, res);
|
3567 | }));
|
3568 | }
|
3569 |
|
3570 | return this;
|
3571 | }
|
3572 |
|
3573 | if (runValidators) {
|
3574 | this.validate(this._update, opts, isOverwriting, function(error) {
|
3575 | if (error) {
|
3576 | return callback(error);
|
3577 | }
|
3578 | _legacyFindAndModify.call(_this, castedQuery, _this._update, opts, cb);
|
3579 | });
|
3580 | } else {
|
3581 | _legacyFindAndModify.call(_this, castedQuery, _this._update, opts, cb);
|
3582 | }
|
3583 |
|
3584 | return this;
|
3585 | };
|
3586 |
|
3587 | /*!
|
3588 | * ignore
|
3589 | */
|
3590 |
|
3591 | function _completeOneLean(doc, res, opts, callback) {
|
3592 | if (opts.rawResult) {
|
3593 | return callback(null, res);
|
3594 | }
|
3595 | return callback(null, doc);
|
3596 | }
|
3597 |
|
3598 |
|
3599 | /*!
|
3600 | * ignore
|
3601 | */
|
3602 |
|
3603 | const _legacyFindAndModify = util.deprecate(function(filter, update, opts, cb) {
|
3604 | if (update && update.toBSON) {
|
3605 | update = update.toBSON();
|
3606 | }
|
3607 | const collection = this._collection;
|
3608 | const sort = opts != null && Array.isArray(opts.sort) ? opts.sort : [];
|
3609 | const _cb = _wrapThunkCallback(this, function(error, res) {
|
3610 | return cb(error, res ? res.value : res, res);
|
3611 | });
|
3612 | collection.collection._findAndModify(filter, sort, update, opts, _cb);
|
3613 | }, 'Mongoose: `findOneAndUpdate()` and `findOneAndDelete()` without the ' +
|
3614 | '`useFindAndModify` option set to false are deprecated. See: ' +
|
3615 | 'https://mongoosejs.com/docs/deprecations.html#-findandmodify-');
|
3616 |
|
3617 | /*!
|
3618 | * Override mquery.prototype._mergeUpdate to handle mongoose objects in
|
3619 | * updates.
|
3620 | *
|
3621 | * @param {Object} doc
|
3622 | * @api private
|
3623 | */
|
3624 |
|
3625 | Query.prototype._mergeUpdate = function(doc) {
|
3626 | if (doc == null || (typeof doc === 'object' && Object.keys(doc).length === 0)) {
|
3627 | return;
|
3628 | }
|
3629 |
|
3630 | if (!this._update) {
|
3631 | this._update = Array.isArray(doc) ? [] : {};
|
3632 | }
|
3633 | if (doc instanceof Query) {
|
3634 | if (Array.isArray(this._update)) {
|
3635 | throw new Error('Cannot mix array and object updates');
|
3636 | }
|
3637 | if (doc._update) {
|
3638 | utils.mergeClone(this._update, doc._update);
|
3639 | }
|
3640 | } else if (Array.isArray(doc)) {
|
3641 | if (!Array.isArray(this._update)) {
|
3642 | throw new Error('Cannot mix array and object updates');
|
3643 | }
|
3644 | this._update = this._update.concat(doc);
|
3645 | } else {
|
3646 | if (Array.isArray(this._update)) {
|
3647 | throw new Error('Cannot mix array and object updates');
|
3648 | }
|
3649 | utils.mergeClone(this._update, doc);
|
3650 | }
|
3651 | };
|
3652 |
|
3653 | /*!
|
3654 | * The mongodb driver 1.3.23 only supports the nested array sort
|
3655 | * syntax. We must convert it or sorting findAndModify will not work.
|
3656 | */
|
3657 |
|
3658 | function convertSortToArray(opts) {
|
3659 | if (Array.isArray(opts.sort)) {
|
3660 | return;
|
3661 | }
|
3662 | if (!utils.isObject(opts.sort)) {
|
3663 | return;
|
3664 | }
|
3665 |
|
3666 | const sort = [];
|
3667 |
|
3668 | for (const key in opts.sort) {
|
3669 | if (utils.object.hasOwnProperty(opts.sort, key)) {
|
3670 | sort.push([key, opts.sort[key]]);
|
3671 | }
|
3672 | }
|
3673 |
|
3674 | opts.sort = sort;
|
3675 | }
|
3676 |
|
3677 | /*!
|
3678 | * ignore
|
3679 | */
|
3680 |
|
3681 | function _updateThunk(op, callback) {
|
3682 | this._castConditions();
|
3683 |
|
3684 | _castArrayFilters(this);
|
3685 |
|
3686 | if (this.error() != null) {
|
3687 | callback(this.error());
|
3688 | return null;
|
3689 | }
|
3690 |
|
3691 | callback = _wrapThunkCallback(this, callback);
|
3692 |
|
3693 | const castedQuery = this._conditions;
|
3694 | const options = this._optionsForExec(this.model);
|
3695 |
|
3696 | ++this._executionCount;
|
3697 |
|
3698 | this._update = utils.clone(this._update, options);
|
3699 | const isOverwriting = this.options.overwrite && !hasDollarKeys(this._update);
|
3700 | if (isOverwriting) {
|
3701 | if (op === 'updateOne' || op === 'updateMany') {
|
3702 | return callback(new MongooseError('The MongoDB server disallows ' +
|
3703 | 'overwriting documents using `' + op + '`. See: ' +
|
3704 | 'https://mongoosejs.com/docs/deprecations.html#-update-'));
|
3705 | }
|
3706 | this._update = new this.model(this._update, null, true);
|
3707 | } else {
|
3708 | this._update = castDoc(this, options.overwrite);
|
3709 |
|
3710 | if (this._update instanceof Error) {
|
3711 | callback(this._update);
|
3712 | return null;
|
3713 | }
|
3714 |
|
3715 | if (this._update == null || Object.keys(this._update).length === 0) {
|
3716 | callback(null, 0);
|
3717 | return null;
|
3718 | }
|
3719 |
|
3720 | this._update = setDefaultsOnInsert(this._conditions, this.model.schema,
|
3721 | this._update, options);
|
3722 | }
|
3723 |
|
3724 | const runValidators = _getOption(this, 'runValidators', false);
|
3725 | if (runValidators) {
|
3726 | this.validate(this._update, options, isOverwriting, err => {
|
3727 | if (err) {
|
3728 | return callback(err);
|
3729 | }
|
3730 |
|
3731 | if (this._update.toBSON) {
|
3732 | this._update = this._update.toBSON();
|
3733 | }
|
3734 | this._collection[op](castedQuery, this._update, options, callback);
|
3735 | });
|
3736 | return null;
|
3737 | }
|
3738 |
|
3739 | if (this._update.toBSON) {
|
3740 | this._update = this._update.toBSON();
|
3741 | }
|
3742 |
|
3743 | this._collection[op](castedQuery, this._update, options, callback);
|
3744 | return null;
|
3745 | }
|
3746 |
|
3747 | /*!
|
3748 | * Mongoose calls this function internally to validate the query if
|
3749 | * `runValidators` is set
|
3750 | *
|
3751 | * @param {Object} castedDoc the update, after casting
|
3752 | * @param {Object} options the options from `_optionsForExec()`
|
3753 | * @param {Function} callback
|
3754 | * @api private
|
3755 | */
|
3756 |
|
3757 | Query.prototype.validate = function validate(castedDoc, options, isOverwriting, callback) {
|
3758 | return promiseOrCallback(callback, cb => {
|
3759 | try {
|
3760 | if (isOverwriting) {
|
3761 | castedDoc.validate(cb);
|
3762 | } else {
|
3763 | updateValidators(this, this.model.schema, castedDoc, options, cb);
|
3764 | }
|
3765 | } catch (err) {
|
3766 | process.nextTick(function() {
|
3767 | cb(err);
|
3768 | });
|
3769 | }
|
3770 | });
|
3771 | };
|
3772 |
|
3773 | /*!
|
3774 | * Internal thunk for .update()
|
3775 | *
|
3776 | * @param {Function} callback
|
3777 | * @see Model.update #model_Model.update
|
3778 | * @api private
|
3779 | */
|
3780 | Query.prototype._execUpdate = wrapThunk(function(callback) {
|
3781 | return _updateThunk.call(this, 'update', callback);
|
3782 | });
|
3783 |
|
3784 | /*!
|
3785 | * Internal thunk for .updateMany()
|
3786 | *
|
3787 | * @param {Function} callback
|
3788 | * @see Model.update #model_Model.update
|
3789 | * @api private
|
3790 | */
|
3791 | Query.prototype._updateMany = wrapThunk(function(callback) {
|
3792 | return _updateThunk.call(this, 'updateMany', callback);
|
3793 | });
|
3794 |
|
3795 | /*!
|
3796 | * Internal thunk for .updateOne()
|
3797 | *
|
3798 | * @param {Function} callback
|
3799 | * @see Model.update #model_Model.update
|
3800 | * @api private
|
3801 | */
|
3802 | Query.prototype._updateOne = wrapThunk(function(callback) {
|
3803 | return _updateThunk.call(this, 'updateOne', callback);
|
3804 | });
|
3805 |
|
3806 | /*!
|
3807 | * Internal thunk for .replaceOne()
|
3808 | *
|
3809 | * @param {Function} callback
|
3810 | * @see Model.replaceOne #model_Model.replaceOne
|
3811 | * @api private
|
3812 | */
|
3813 | Query.prototype._replaceOne = wrapThunk(function(callback) {
|
3814 | return _updateThunk.call(this, 'replaceOne', callback);
|
3815 | });
|
3816 |
|
3817 | /**
|
3818 | * Declare and/or execute this query as an update() operation.
|
3819 | *
|
3820 | * _All paths passed that are not [atomic](https://docs.mongodb.com/manual/tutorial/model-data-for-atomic-operations/#pattern) operations will become `$set` ops._
|
3821 | *
|
3822 | * This function triggers the following middleware.
|
3823 | *
|
3824 | * - `update()`
|
3825 | *
|
3826 | * ####Example
|
3827 | *
|
3828 | * Model.where({ _id: id }).update({ title: 'words' })
|
3829 | *
|
3830 | * // becomes
|
3831 | *
|
3832 | * Model.where({ _id: id }).update({ $set: { title: 'words' }})
|
3833 | *
|
3834 | * ####Valid options:
|
3835 | *
|
3836 | * - `upsert` (boolean) whether to create the doc if it doesn't match (false)
|
3837 | * - `multi` (boolean) whether multiple documents should be updated (false)
|
3838 | * - `runValidators`: if true, runs [update validators](/docs/validation.html#update-validators) on this command. Update validators validate the update operation against the model's schema.
|
3839 | * - `setDefaultsOnInsert`: if this and `upsert` are true, mongoose will apply the [defaults](http://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created. This option only works on MongoDB >= 2.4 because it relies on [MongoDB's `$setOnInsert` operator](https://docs.mongodb.org/v2.4/reference/operator/update/setOnInsert/).
|
3840 | * - `strict` (boolean) overrides the `strict` option for this update
|
3841 | * - `overwrite` (boolean) disables update-only mode, allowing you to overwrite the doc (false)
|
3842 | * - `context` (string) if set to 'query' and `runValidators` is on, `this` will refer to the query in custom validator functions that update validation runs. Does nothing if `runValidators` is false.
|
3843 | * - `read`
|
3844 | * - `writeConcern`
|
3845 | *
|
3846 | * ####Note
|
3847 | *
|
3848 | * Passing an empty object `{}` as the doc will result in a no-op unless the `overwrite` option is passed. Without the `overwrite` option set, the update operation will be ignored and the callback executed without sending the command to MongoDB so as to prevent accidently overwritting documents in the collection.
|
3849 | *
|
3850 | * ####Note
|
3851 | *
|
3852 | * The operation is only executed when a callback is passed. To force execution without a callback, we must first call update() and then execute it by using the `exec()` method.
|
3853 | *
|
3854 | * var q = Model.where({ _id: id });
|
3855 | * q.update({ $set: { name: 'bob' }}).update(); // not executed
|
3856 | *
|
3857 | * q.update({ $set: { name: 'bob' }}).exec(); // executed
|
3858 | *
|
3859 | * // keys that are not [atomic](https://docs.mongodb.com/manual/tutorial/model-data-for-atomic-operations/#pattern) ops become `$set`.
|
3860 | * // this executes the same command as the previous example.
|
3861 | * q.update({ name: 'bob' }).exec();
|
3862 | *
|
3863 | * // overwriting with empty docs
|
3864 | * var q = Model.where({ _id: id }).setOptions({ overwrite: true })
|
3865 | * q.update({ }, callback); // executes
|
3866 | *
|
3867 | * // multi update with overwrite to empty doc
|
3868 | * var q = Model.where({ _id: id });
|
3869 | * q.setOptions({ multi: true, overwrite: true })
|
3870 | * q.update({ });
|
3871 | * q.update(callback); // executed
|
3872 | *
|
3873 | * // multi updates
|
3874 | * Model.where()
|
3875 | * .update({ name: /^match/ }, { $set: { arr: [] }}, { multi: true }, callback)
|
3876 | *
|
3877 | * // more multi updates
|
3878 | * Model.where()
|
3879 | * .setOptions({ multi: true })
|
3880 | * .update({ $set: { arr: [] }}, callback)
|
3881 | *
|
3882 | * // single update by default
|
3883 | * Model.where({ email: 'address@example.com' })
|
3884 | * .update({ $inc: { counter: 1 }}, callback)
|
3885 | *
|
3886 | * API summary
|
3887 | *
|
3888 | * update(filter, doc, options, cb) // executes
|
3889 | * update(filter, doc, options)
|
3890 | * update(filter, doc, cb) // executes
|
3891 | * update(filter, doc)
|
3892 | * update(doc, cb) // executes
|
3893 | * update(doc)
|
3894 | * update(cb) // executes
|
3895 | * update(true) // executes
|
3896 | * update()
|
3897 | *
|
3898 | * @param {Object} [filter]
|
3899 | * @param {Object} [doc] the update command
|
3900 | * @param {Object} [options]
|
3901 | * @param {Boolean} [options.multipleCastError] by default, mongoose only returns the first error that occurred in casting the query. Turn on this option to aggregate all the cast errors.
|
3902 | * @param {Boolean} [options.omitUndefined=false] If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server.
|
3903 | * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
|
3904 | * @param {Boolean} [options.upsert=false] if true, and no documents found, insert a new document
|
3905 | * @param {Object} [options.writeConcern=null] sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](/docs/guide.html#writeConcern)
|
3906 | * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set.
|
3907 | * @param {Function} [callback] params are (error, writeOpResult)
|
3908 | * @return {Query} this
|
3909 | * @see Model.update #model_Model.update
|
3910 | * @see Query docs https://mongoosejs.com/docs/queries.html
|
3911 | * @see update http://docs.mongodb.org/manual/reference/method/db.collection.update/
|
3912 | * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult
|
3913 | * @see MongoDB docs https://docs.mongodb.com/manual/reference/command/update/#update-command-output
|
3914 | * @api public
|
3915 | */
|
3916 |
|
3917 | Query.prototype.update = function(conditions, doc, options, callback) {
|
3918 | if (typeof options === 'function') {
|
3919 | // .update(conditions, doc, callback)
|
3920 | callback = options;
|
3921 | options = null;
|
3922 | } else if (typeof doc === 'function') {
|
3923 | // .update(doc, callback);
|
3924 | callback = doc;
|
3925 | doc = conditions;
|
3926 | conditions = {};
|
3927 | options = null;
|
3928 | } else if (typeof conditions === 'function') {
|
3929 | // .update(callback)
|
3930 | callback = conditions;
|
3931 | conditions = undefined;
|
3932 | doc = undefined;
|
3933 | options = undefined;
|
3934 | } else if (typeof conditions === 'object' && !doc && !options && !callback) {
|
3935 | // .update(doc)
|
3936 | doc = conditions;
|
3937 | conditions = undefined;
|
3938 | options = undefined;
|
3939 | callback = undefined;
|
3940 | }
|
3941 |
|
3942 | return _update(this, 'update', conditions, doc, options, callback);
|
3943 | };
|
3944 |
|
3945 | /**
|
3946 | * Declare and/or execute this query as an updateMany() operation. Same as
|
3947 | * `update()`, except MongoDB will update _all_ documents that match
|
3948 | * `filter` (as opposed to just the first one) regardless of the value of
|
3949 | * the `multi` option.
|
3950 | *
|
3951 | * **Note** updateMany will _not_ fire update middleware. Use `pre('updateMany')`
|
3952 | * and `post('updateMany')` instead.
|
3953 | *
|
3954 | * ####Example:
|
3955 | * const res = await Person.updateMany({ name: /Stark$/ }, { isDeleted: true });
|
3956 | * res.n; // Number of documents matched
|
3957 | * res.nModified; // Number of documents modified
|
3958 | *
|
3959 | * This function triggers the following middleware.
|
3960 | *
|
3961 | * - `updateMany()`
|
3962 | *
|
3963 | * @param {Object} [filter]
|
3964 | * @param {Object} [doc] the update command
|
3965 | * @param {Object} [options]
|
3966 | * @param {Boolean} [options.multipleCastError] by default, mongoose only returns the first error that occurred in casting the query. Turn on this option to aggregate all the cast errors.
|
3967 | * @param {Boolean} [options.omitUndefined=false] If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server.
|
3968 | * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
|
3969 | * @param {Boolean} [options.upsert=false] if true, and no documents found, insert a new document
|
3970 | * @param {Object} [options.writeConcern=null] sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](/docs/guide.html#writeConcern)
|
3971 | * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set.
|
3972 | * @param {Function} [callback] params are (error, writeOpResult)
|
3973 | * @return {Query} this
|
3974 | * @see Model.update #model_Model.update
|
3975 | * @see Query docs https://mongoosejs.com/docs/queries.html
|
3976 | * @see update http://docs.mongodb.org/manual/reference/method/db.collection.update/
|
3977 | * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult
|
3978 | * @see MongoDB docs https://docs.mongodb.com/manual/reference/command/update/#update-command-output
|
3979 | * @api public
|
3980 | */
|
3981 |
|
3982 | Query.prototype.updateMany = function(conditions, doc, options, callback) {
|
3983 | if (typeof options === 'function') {
|
3984 | // .update(conditions, doc, callback)
|
3985 | callback = options;
|
3986 | options = null;
|
3987 | } else if (typeof doc === 'function') {
|
3988 | // .update(doc, callback);
|
3989 | callback = doc;
|
3990 | doc = conditions;
|
3991 | conditions = {};
|
3992 | options = null;
|
3993 | } else if (typeof conditions === 'function') {
|
3994 | // .update(callback)
|
3995 | callback = conditions;
|
3996 | conditions = undefined;
|
3997 | doc = undefined;
|
3998 | options = undefined;
|
3999 | } else if (typeof conditions === 'object' && !doc && !options && !callback) {
|
4000 | // .update(doc)
|
4001 | doc = conditions;
|
4002 | conditions = undefined;
|
4003 | options = undefined;
|
4004 | callback = undefined;
|
4005 | }
|
4006 |
|
4007 | return _update(this, 'updateMany', conditions, doc, options, callback);
|
4008 | };
|
4009 |
|
4010 | /**
|
4011 | * Declare and/or execute this query as an updateOne() operation. Same as
|
4012 | * `update()`, except it does not support the `multi` or `overwrite` options.
|
4013 | *
|
4014 | * - MongoDB will update _only_ the first document that matches `filter` regardless of the value of the `multi` option.
|
4015 | * - Use `replaceOne()` if you want to overwrite an entire document rather than using [atomic](https://docs.mongodb.com/manual/tutorial/model-data-for-atomic-operations/#pattern) operators like `$set`.
|
4016 | *
|
4017 | * **Note** updateOne will _not_ fire update middleware. Use `pre('updateOne')`
|
4018 | * and `post('updateOne')` instead.
|
4019 | *
|
4020 | * ####Example:
|
4021 | * const res = await Person.updateOne({ name: 'Jean-Luc Picard' }, { ship: 'USS Enterprise' });
|
4022 | * res.n; // Number of documents matched
|
4023 | * res.nModified; // Number of documents modified
|
4024 | *
|
4025 | * This function triggers the following middleware.
|
4026 | *
|
4027 | * - `updateOne()`
|
4028 | *
|
4029 | * @param {Object} [filter]
|
4030 | * @param {Object} [doc] the update command
|
4031 | * @param {Object} [options]
|
4032 | * @param {Boolean} [options.multipleCastError] by default, mongoose only returns the first error that occurred in casting the query. Turn on this option to aggregate all the cast errors.
|
4033 | * @param {Boolean} [options.omitUndefined=false] If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server.
|
4034 | * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
|
4035 | * @param {Boolean} [options.upsert=false] if true, and no documents found, insert a new document
|
4036 | * @param {Object} [options.writeConcern=null] sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](/docs/guide.html#writeConcern)
|
4037 | * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set.
|
4038 | * @param {Function} [callback] params are (error, writeOpResult)
|
4039 | * @return {Query} this
|
4040 | * @see Model.update #model_Model.update
|
4041 | * @see Query docs https://mongoosejs.com/docs/queries.html
|
4042 | * @see update http://docs.mongodb.org/manual/reference/method/db.collection.update/
|
4043 | * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult
|
4044 | * @see MongoDB docs https://docs.mongodb.com/manual/reference/command/update/#update-command-output
|
4045 | * @api public
|
4046 | */
|
4047 |
|
4048 | Query.prototype.updateOne = function(conditions, doc, options, callback) {
|
4049 | if (typeof options === 'function') {
|
4050 | // .update(conditions, doc, callback)
|
4051 | callback = options;
|
4052 | options = null;
|
4053 | } else if (typeof doc === 'function') {
|
4054 | // .update(doc, callback);
|
4055 | callback = doc;
|
4056 | doc = conditions;
|
4057 | conditions = {};
|
4058 | options = null;
|
4059 | } else if (typeof conditions === 'function') {
|
4060 | // .update(callback)
|
4061 | callback = conditions;
|
4062 | conditions = undefined;
|
4063 | doc = undefined;
|
4064 | options = undefined;
|
4065 | } else if (typeof conditions === 'object' && !doc && !options && !callback) {
|
4066 | // .update(doc)
|
4067 | doc = conditions;
|
4068 | conditions = undefined;
|
4069 | options = undefined;
|
4070 | callback = undefined;
|
4071 | }
|
4072 |
|
4073 | return _update(this, 'updateOne', conditions, doc, options, callback);
|
4074 | };
|
4075 |
|
4076 | /**
|
4077 | * Declare and/or execute this query as a replaceOne() operation. Same as
|
4078 | * `update()`, except MongoDB will replace the existing document and will
|
4079 | * not accept any [atomic](https://docs.mongodb.com/manual/tutorial/model-data-for-atomic-operations/#pattern) operators (`$set`, etc.)
|
4080 | *
|
4081 | * **Note** replaceOne will _not_ fire update middleware. Use `pre('replaceOne')`
|
4082 | * and `post('replaceOne')` instead.
|
4083 | *
|
4084 | * ####Example:
|
4085 | * const res = await Person.replaceOne({ _id: 24601 }, { name: 'Jean Valjean' });
|
4086 | * res.n; // Number of documents matched
|
4087 | * res.nModified; // Number of documents modified
|
4088 | *
|
4089 | * This function triggers the following middleware.
|
4090 | *
|
4091 | * - `replaceOne()`
|
4092 | *
|
4093 | * @param {Object} [filter]
|
4094 | * @param {Object} [doc] the update command
|
4095 | * @param {Object} [options]
|
4096 | * @param {Boolean} [options.multipleCastError] by default, mongoose only returns the first error that occurred in casting the query. Turn on this option to aggregate all the cast errors.
|
4097 | * @param {Boolean} [options.omitUndefined=false] If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server.
|
4098 | * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
|
4099 | * @param {Boolean} [options.upsert=false] if true, and no documents found, insert a new document
|
4100 | * @param {Object} [options.writeConcern=null] sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](/docs/guide.html#writeConcern)
|
4101 | * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set.
|
4102 | * @param {Function} [callback] params are (error, writeOpResult)
|
4103 | * @return {Query} this
|
4104 | * @see Model.update #model_Model.update
|
4105 | * @see Query docs https://mongoosejs.com/docs/queries.html
|
4106 | * @see update http://docs.mongodb.org/manual/reference/method/db.collection.update/
|
4107 | * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult
|
4108 | * @see MongoDB docs https://docs.mongodb.com/manual/reference/command/update/#update-command-output
|
4109 | * @api public
|
4110 | */
|
4111 |
|
4112 | Query.prototype.replaceOne = function(conditions, doc, options, callback) {
|
4113 | if (typeof options === 'function') {
|
4114 | // .update(conditions, doc, callback)
|
4115 | callback = options;
|
4116 | options = null;
|
4117 | } else if (typeof doc === 'function') {
|
4118 | // .update(doc, callback);
|
4119 | callback = doc;
|
4120 | doc = conditions;
|
4121 | conditions = {};
|
4122 | options = null;
|
4123 | } else if (typeof conditions === 'function') {
|
4124 | // .update(callback)
|
4125 | callback = conditions;
|
4126 | conditions = undefined;
|
4127 | doc = undefined;
|
4128 | options = undefined;
|
4129 | } else if (typeof conditions === 'object' && !doc && !options && !callback) {
|
4130 | // .update(doc)
|
4131 | doc = conditions;
|
4132 | conditions = undefined;
|
4133 | options = undefined;
|
4134 | callback = undefined;
|
4135 | }
|
4136 |
|
4137 | this.setOptions({ overwrite: true });
|
4138 | return _update(this, 'replaceOne', conditions, doc, options, callback);
|
4139 | };
|
4140 |
|
4141 | /*!
|
4142 | * Internal helper for update, updateMany, updateOne, replaceOne
|
4143 | */
|
4144 |
|
4145 | function _update(query, op, filter, doc, options, callback) {
|
4146 | // make sure we don't send in the whole Document to merge()
|
4147 | query.op = op;
|
4148 | filter = utils.toObject(filter);
|
4149 | doc = doc || {};
|
4150 |
|
4151 | const oldCb = callback;
|
4152 | if (oldCb) {
|
4153 | if (typeof oldCb === 'function') {
|
4154 | callback = function(error, result) {
|
4155 | oldCb(error, result ? result.result : {ok: 0, n: 0, nModified: 0});
|
4156 | };
|
4157 | } else {
|
4158 | throw new Error('Invalid callback() argument.');
|
4159 | }
|
4160 | }
|
4161 |
|
4162 | // strict is an option used in the update checking, make sure it gets set
|
4163 | if (options != null) {
|
4164 | if ('strict' in options) {
|
4165 | query._mongooseOptions.strict = options.strict;
|
4166 | }
|
4167 | }
|
4168 |
|
4169 | if (!(filter instanceof Query) &&
|
4170 | filter != null &&
|
4171 | filter.toString() !== '[object Object]') {
|
4172 | query.error(new ObjectParameterError(filter, 'filter', op));
|
4173 | } else {
|
4174 | query.merge(filter);
|
4175 | }
|
4176 |
|
4177 | if (utils.isObject(options)) {
|
4178 | query.setOptions(options);
|
4179 | }
|
4180 |
|
4181 | query._mergeUpdate(doc);
|
4182 |
|
4183 | // Hooks
|
4184 | if (callback) {
|
4185 | if (op === 'update') {
|
4186 | query._execUpdate(callback);
|
4187 | return query;
|
4188 | }
|
4189 | query['_' + op](callback);
|
4190 | return query;
|
4191 | }
|
4192 |
|
4193 | return Query.base[op].call(query, filter, void 0, options, callback);
|
4194 | }
|
4195 |
|
4196 | /**
|
4197 | * Runs a function `fn` and treats the return value of `fn` as the new value
|
4198 | * for the query to resolve to.
|
4199 | *
|
4200 | * Any functions you pass to `map()` will run **after** any post hooks.
|
4201 | *
|
4202 | * ####Example:
|
4203 | *
|
4204 | * const res = await MyModel.findOne().map(res => {
|
4205 | * // Sets a `loadedAt` property on the doc that tells you the time the
|
4206 | * // document was loaded.
|
4207 | * return res == null ?
|
4208 | * res :
|
4209 | * Object.assign(res, { loadedAt: new Date() });
|
4210 | * });
|
4211 | *
|
4212 | * @method map
|
4213 | * @memberOf Query
|
4214 | * @instance
|
4215 | * @param {Function} fn function to run to transform the query result
|
4216 | * @return {Query} this
|
4217 | */
|
4218 |
|
4219 | Query.prototype.map = function(fn) {
|
4220 | this._transforms.push(fn);
|
4221 | return this;
|
4222 | };
|
4223 |
|
4224 | /**
|
4225 | * Make this query throw an error if no documents match the given `filter`.
|
4226 | * This is handy for integrating with async/await, because `orFail()` saves you
|
4227 | * an extra `if` statement to check if no document was found.
|
4228 | *
|
4229 | * ####Example:
|
4230 | *
|
4231 | * // Throws if no doc returned
|
4232 | * await Model.findOne({ foo: 'bar' }).orFail();
|
4233 | *
|
4234 | * // Throws if no document was updated
|
4235 | * await Model.updateOne({ foo: 'bar' }, { name: 'test' }).orFail();
|
4236 | *
|
4237 | * // Throws "No docs found!" error if no docs match `{ foo: 'bar' }`
|
4238 | * await Model.find({ foo: 'bar' }).orFail(new Error('No docs found!'));
|
4239 | *
|
4240 | * // Throws "Not found" error if no document was found
|
4241 | * await Model.findOneAndUpdate({ foo: 'bar' }, { name: 'test' }).
|
4242 | * orFail(() => Error('Not found'));
|
4243 | *
|
4244 | * @method orFail
|
4245 | * @memberOf Query
|
4246 | * @instance
|
4247 | * @param {Function|Error} [err] optional error to throw if no docs match `filter`. If not specified, `orFail()` will throw a `DocumentNotFoundError`
|
4248 | * @return {Query} this
|
4249 | */
|
4250 |
|
4251 | Query.prototype.orFail = function(err) {
|
4252 | this.map(res => {
|
4253 | switch (this.op) {
|
4254 | case 'find':
|
4255 | if (res.length === 0) {
|
4256 | throw _orFailError(err, this);
|
4257 | }
|
4258 | break;
|
4259 | case 'findOne':
|
4260 | if (res == null) {
|
4261 | throw _orFailError(err, this);
|
4262 | }
|
4263 | break;
|
4264 | case 'update':
|
4265 | case 'updateMany':
|
4266 | case 'updateOne':
|
4267 | if (get(res, 'result.nModified') === 0) {
|
4268 | throw _orFailError(err, this);
|
4269 | }
|
4270 | break;
|
4271 | case 'findOneAndDelete':
|
4272 | if (get(res, 'lastErrorObject.n') === 0) {
|
4273 | throw _orFailError(err, this);
|
4274 | }
|
4275 | break;
|
4276 | case 'findOneAndUpdate':
|
4277 | case 'findOneAndReplace':
|
4278 | if (get(res, 'lastErrorObject.updatedExisting') === false) {
|
4279 | throw _orFailError(err, this);
|
4280 | }
|
4281 | break;
|
4282 | case 'deleteMany':
|
4283 | case 'deleteOne':
|
4284 | case 'remove':
|
4285 | if (res.n === 0) {
|
4286 | throw _orFailError(err, this);
|
4287 | }
|
4288 | break;
|
4289 | default:
|
4290 | break;
|
4291 | }
|
4292 |
|
4293 | return res;
|
4294 | });
|
4295 | return this;
|
4296 | };
|
4297 |
|
4298 | /*!
|
4299 | * Get the error to throw for `orFail()`
|
4300 | */
|
4301 |
|
4302 | function _orFailError(err, query) {
|
4303 | if (typeof err === 'function') {
|
4304 | err = err.call(query);
|
4305 | }
|
4306 |
|
4307 | if (err == null) {
|
4308 | err = new DocumentNotFoundError(query.getQuery(), query.model.modelName);
|
4309 | }
|
4310 |
|
4311 | return err;
|
4312 | }
|
4313 |
|
4314 | /**
|
4315 | * Executes the query
|
4316 | *
|
4317 | * ####Examples:
|
4318 | *
|
4319 | * var promise = query.exec();
|
4320 | * var promise = query.exec('update');
|
4321 | *
|
4322 | * query.exec(callback);
|
4323 | * query.exec('find', callback);
|
4324 | *
|
4325 | * @param {String|Function} [operation]
|
4326 | * @param {Function} [callback] optional params depend on the function being called
|
4327 | * @return {Promise}
|
4328 | * @api public
|
4329 | */
|
4330 |
|
4331 | Query.prototype.exec = function exec(op, callback) {
|
4332 | const _this = this;
|
4333 |
|
4334 | if (typeof op === 'function') {
|
4335 | callback = op;
|
4336 | op = null;
|
4337 | } else if (typeof op === 'string') {
|
4338 | this.op = op;
|
4339 | }
|
4340 |
|
4341 | callback = this.model.$handleCallbackError(callback);
|
4342 |
|
4343 | return promiseOrCallback(callback, (cb) => {
|
4344 | cb = this.model.$wrapCallback(cb);
|
4345 |
|
4346 | if (!_this.op) {
|
4347 | cb();
|
4348 | return;
|
4349 | }
|
4350 |
|
4351 | this._hooks.execPre('exec', this, [], (error) => {
|
4352 | if (error != null) {
|
4353 | return cb(error);
|
4354 | }
|
4355 | this[this.op].call(this, (error, res) => {
|
4356 | if (error) {
|
4357 | return cb(error);
|
4358 | }
|
4359 |
|
4360 | this._hooks.execPost('exec', this, [], {}, (error) => {
|
4361 | if (error) {
|
4362 | return cb(error);
|
4363 | }
|
4364 |
|
4365 | cb(null, res);
|
4366 | });
|
4367 | });
|
4368 | });
|
4369 | }, this.model.events);
|
4370 | };
|
4371 |
|
4372 | /*!
|
4373 | * ignore
|
4374 | */
|
4375 |
|
4376 | function _wrapThunkCallback(query, cb) {
|
4377 | return function(error, res) {
|
4378 | if (error != null) {
|
4379 | return cb(error);
|
4380 | }
|
4381 |
|
4382 | for (const fn of query._transforms) {
|
4383 | try {
|
4384 | res = fn(res);
|
4385 | } catch (error) {
|
4386 | return cb(error);
|
4387 | }
|
4388 | }
|
4389 |
|
4390 | return cb(null, res);
|
4391 | };
|
4392 | }
|
4393 |
|
4394 | /**
|
4395 | * Executes the query returning a `Promise` which will be
|
4396 | * resolved with either the doc(s) or rejected with the error.
|
4397 | *
|
4398 | * @param {Function} [resolve]
|
4399 | * @param {Function} [reject]
|
4400 | * @return {Promise}
|
4401 | * @api public
|
4402 | */
|
4403 |
|
4404 | Query.prototype.then = function(resolve, reject) {
|
4405 | return this.exec().then(resolve, reject);
|
4406 | };
|
4407 |
|
4408 | /**
|
4409 | * Executes the query returning a `Promise` which will be
|
4410 | * resolved with either the doc(s) or rejected with the error.
|
4411 | * Like `.then()`, but only takes a rejection handler.
|
4412 | *
|
4413 | * @param {Function} [reject]
|
4414 | * @return {Promise}
|
4415 | * @api public
|
4416 | */
|
4417 |
|
4418 | Query.prototype.catch = function(reject) {
|
4419 | return this.exec().then(null, reject);
|
4420 | };
|
4421 |
|
4422 | /*!
|
4423 | * ignore
|
4424 | */
|
4425 |
|
4426 | Query.prototype._pre = function(fn) {
|
4427 | this._hooks.pre('exec', fn);
|
4428 | return this;
|
4429 | };
|
4430 |
|
4431 | /*!
|
4432 | * ignore
|
4433 | */
|
4434 |
|
4435 | Query.prototype._post = function(fn) {
|
4436 | this._hooks.post('exec', fn);
|
4437 | return this;
|
4438 | };
|
4439 |
|
4440 | /*!
|
4441 | * Casts obj for an update command.
|
4442 | *
|
4443 | * @param {Object} obj
|
4444 | * @return {Object} obj after casting its values
|
4445 | * @api private
|
4446 | */
|
4447 |
|
4448 | Query.prototype._castUpdate = function _castUpdate(obj, overwrite) {
|
4449 | let strict;
|
4450 | if ('strict' in this._mongooseOptions) {
|
4451 | strict = this._mongooseOptions.strict;
|
4452 | } else if (this.schema && this.schema.options) {
|
4453 | strict = this.schema.options.strict;
|
4454 | } else {
|
4455 | strict = true;
|
4456 | }
|
4457 |
|
4458 | let omitUndefined = false;
|
4459 | if ('omitUndefined' in this._mongooseOptions) {
|
4460 | omitUndefined = this._mongooseOptions.omitUndefined;
|
4461 | }
|
4462 |
|
4463 | let useNestedStrict;
|
4464 | if ('useNestedStrict' in this.options) {
|
4465 | useNestedStrict = this.options.useNestedStrict;
|
4466 | }
|
4467 |
|
4468 | let schema = this.schema;
|
4469 | const filter = this._conditions;
|
4470 | if (schema != null &&
|
4471 | utils.hasUserDefinedProperty(filter, schema.options.discriminatorKey) &&
|
4472 | typeof filter[schema.options.discriminatorKey] !== 'object' &&
|
4473 | schema.discriminators != null) {
|
4474 | const discriminatorValue = filter[schema.options.discriminatorKey];
|
4475 | const byValue = getDiscriminatorByValue(this.model, discriminatorValue);
|
4476 | schema = schema.discriminators[discriminatorValue] ||
|
4477 | (byValue && byValue.schema) ||
|
4478 | schema;
|
4479 | }
|
4480 |
|
4481 | return castUpdate(schema, obj, {
|
4482 | overwrite: overwrite,
|
4483 | strict: strict,
|
4484 | omitUndefined,
|
4485 | useNestedStrict: useNestedStrict
|
4486 | }, this, this._conditions);
|
4487 | };
|
4488 |
|
4489 | /*!
|
4490 | * castQuery
|
4491 | * @api private
|
4492 | */
|
4493 |
|
4494 | function castQuery(query) {
|
4495 | try {
|
4496 | return query.cast(query.model);
|
4497 | } catch (err) {
|
4498 | return err;
|
4499 | }
|
4500 | }
|
4501 |
|
4502 | /*!
|
4503 | * castDoc
|
4504 | * @api private
|
4505 | */
|
4506 |
|
4507 | function castDoc(query, overwrite) {
|
4508 | try {
|
4509 | return query._castUpdate(query._update, overwrite);
|
4510 | } catch (err) {
|
4511 | return err;
|
4512 | }
|
4513 | }
|
4514 |
|
4515 | /**
|
4516 | * Specifies paths which should be populated with other documents.
|
4517 | *
|
4518 | * ####Example:
|
4519 | *
|
4520 | * Kitten.findOne().populate('owner').exec(function (err, kitten) {
|
4521 | * console.log(kitten.owner.name) // Max
|
4522 | * })
|
4523 | *
|
4524 | * Kitten.find().populate({
|
4525 | * path: 'owner',
|
4526 | * select: 'name',
|
4527 | * match: { color: 'black' },
|
4528 | * options: { sort: { name: -1 } }
|
4529 | * }).exec(function (err, kittens) {
|
4530 | * console.log(kittens[0].owner.name) // Zoopa
|
4531 | * })
|
4532 | *
|
4533 | * // alternatively
|
4534 | * Kitten.find().populate('owner', 'name', null, {sort: { name: -1 }}).exec(function (err, kittens) {
|
4535 | * console.log(kittens[0].owner.name) // Zoopa
|
4536 | * })
|
4537 | *
|
4538 | * Paths are populated after the query executes and a response is received. A
|
4539 | * separate query is then executed for each path specified for population. After
|
4540 | * a response for each query has also been returned, the results are passed to
|
4541 | * the callback.
|
4542 | *
|
4543 | * @param {Object|String} path either the path to populate or an object specifying all parameters
|
4544 | * @param {Object|String} [select] Field selection for the population query
|
4545 | * @param {Model} [model] The model you wish to use for population. If not specified, populate will look up the model by the name in the Schema's `ref` field.
|
4546 | * @param {Object} [match] Conditions for the population query
|
4547 | * @param {Object} [options] Options for the population query (sort, etc)
|
4548 | * @param {String} [options.path=null] The path to populate.
|
4549 | * @param {boolean} [options.retainNullValues=false] by default, Mongoose removes null and undefined values from populated arrays. Use this option to make `populate()` retain `null` and `undefined` array entries.
|
4550 | * @param {boolean} [options.getters=false] if true, Mongoose will call any getters defined on the `localField`. By default, Mongoose gets the raw value of `localField`. For example, you would need to set this option to `true` if you wanted to [add a `lowercase` getter to your `localField`](/docs/schematypes.html#schematype-options).
|
4551 | * @param {boolean} [options.clone=false] When you do `BlogPost.find().populate('author')`, blog posts with the same author will share 1 copy of an `author` doc. Enable this option to make Mongoose clone populated docs before assigning them.
|
4552 | * @param {Object|Function} [options.match=null] Add an additional filter to the populate query. Can be a filter object containing [MongoDB query syntax](https://docs.mongodb.com/manual/tutorial/query-documents/), or a function that returns a filter object.
|
4553 | * @param {Object} [options.options=null] Additional options like `limit` and `lean`.
|
4554 | * @see population ./populate.html
|
4555 | * @see Query#select #query_Query-select
|
4556 | * @see Model.populate #model_Model.populate
|
4557 | * @return {Query} this
|
4558 | * @api public
|
4559 | */
|
4560 |
|
4561 | Query.prototype.populate = function() {
|
4562 | // Bail when given no truthy arguments
|
4563 | if (!Array.from(arguments).some(Boolean)) {
|
4564 | return this;
|
4565 | }
|
4566 |
|
4567 | const res = utils.populate.apply(null, arguments);
|
4568 |
|
4569 | // Propagate readConcern and readPreference and lean from parent query,
|
4570 | // unless one already specified
|
4571 | if (this.options != null) {
|
4572 | const readConcern = this.options.readConcern;
|
4573 | const readPref = this.options.readPreference;
|
4574 |
|
4575 | for (let i = 0; i < res.length; ++i) {
|
4576 | if (readConcern != null && get(res[i], 'options.readConcern') == null) {
|
4577 | res[i].options = res[i].options || {};
|
4578 | res[i].options.readConcern = readConcern;
|
4579 | }
|
4580 | if (readPref != null && get(res[i], 'options.readPreference') == null) {
|
4581 | res[i].options = res[i].options || {};
|
4582 | res[i].options.readPreference = readPref;
|
4583 | }
|
4584 | }
|
4585 | }
|
4586 |
|
4587 | const opts = this._mongooseOptions;
|
4588 |
|
4589 | if (opts.lean != null) {
|
4590 | const lean = opts.lean;
|
4591 | for (let i = 0; i < res.length; ++i) {
|
4592 | if (get(res[i], 'options.lean') == null) {
|
4593 | res[i].options = res[i].options || {};
|
4594 | res[i].options.lean = lean;
|
4595 | }
|
4596 | }
|
4597 | }
|
4598 |
|
4599 | if (!utils.isObject(opts.populate)) {
|
4600 | opts.populate = {};
|
4601 | }
|
4602 |
|
4603 | const pop = opts.populate;
|
4604 |
|
4605 | for (let i = 0; i < res.length; ++i) {
|
4606 | const path = res[i].path;
|
4607 | if (pop[path] && pop[path].populate && res[i].populate) {
|
4608 | res[i].populate = pop[path].populate.concat(res[i].populate);
|
4609 | }
|
4610 | pop[res[i].path] = res[i];
|
4611 | }
|
4612 |
|
4613 | return this;
|
4614 | };
|
4615 |
|
4616 | /**
|
4617 | * Gets a list of paths to be populated by this query
|
4618 | *
|
4619 | * ####Example:
|
4620 | * bookSchema.pre('findOne', function() {
|
4621 | * let keys = this.getPopulatedPaths(); // ['author']
|
4622 | * });
|
4623 | * ...
|
4624 | * Book.findOne({}).populate('author');
|
4625 | *
|
4626 | * ####Example:
|
4627 | * // Deep populate
|
4628 | * const q = L1.find().populate({
|
4629 | * path: 'level2',
|
4630 | * populate: { path: 'level3' }
|
4631 | * });
|
4632 | * q.getPopulatedPaths(); // ['level2', 'level2.level3']
|
4633 | *
|
4634 | * @return {Array} an array of strings representing populated paths
|
4635 | * @api public
|
4636 | */
|
4637 |
|
4638 | Query.prototype.getPopulatedPaths = function getPopulatedPaths() {
|
4639 | const obj = this._mongooseOptions.populate || {};
|
4640 | const ret = Object.keys(obj);
|
4641 | for (const path of Object.keys(obj)) {
|
4642 | const pop = obj[path];
|
4643 | if (!Array.isArray(pop.populate)) {
|
4644 | continue;
|
4645 | }
|
4646 | _getPopulatedPaths(ret, pop.populate, path + '.');
|
4647 | }
|
4648 | return ret;
|
4649 | };
|
4650 |
|
4651 | /*!
|
4652 | * ignore
|
4653 | */
|
4654 |
|
4655 | function _getPopulatedPaths(list, arr, prefix) {
|
4656 | for (const pop of arr) {
|
4657 | list.push(prefix + pop.path);
|
4658 | if (!Array.isArray(pop.populate)) {
|
4659 | continue;
|
4660 | }
|
4661 | _getPopulatedPaths(list, pop.populate, prefix + pop.path + '.');
|
4662 | }
|
4663 | }
|
4664 |
|
4665 | /**
|
4666 | * Casts this query to the schema of `model`
|
4667 | *
|
4668 | * ####Note
|
4669 | *
|
4670 | * If `obj` is present, it is cast instead of this query.
|
4671 | *
|
4672 | * @param {Model} [model] the model to cast to. If not set, defaults to `this.model`
|
4673 | * @param {Object} [obj]
|
4674 | * @return {Object}
|
4675 | * @api public
|
4676 | */
|
4677 |
|
4678 | Query.prototype.cast = function(model, obj) {
|
4679 | obj || (obj = this._conditions);
|
4680 |
|
4681 | model = model || this.model;
|
4682 |
|
4683 | try {
|
4684 | return cast(model.schema, obj, {
|
4685 | upsert: this.options && this.options.upsert,
|
4686 | strict: (this.options && 'strict' in this.options) ?
|
4687 | this.options.strict :
|
4688 | get(model, 'schema.options.strict', null),
|
4689 | strictQuery: (this.options && this.options.strictQuery) ||
|
4690 | get(model, 'schema.options.strictQuery', null)
|
4691 | }, this);
|
4692 | } catch (err) {
|
4693 | // CastError, assign model
|
4694 | if (typeof err.setModel === 'function') {
|
4695 | err.setModel(model);
|
4696 | }
|
4697 | throw err;
|
4698 | }
|
4699 | };
|
4700 |
|
4701 | /**
|
4702 | * Casts selected field arguments for field selection with mongo 2.2
|
4703 | *
|
4704 | * query.select({ ids: { $elemMatch: { $in: [hexString] }})
|
4705 | *
|
4706 | * @param {Object} fields
|
4707 | * @see https://github.com/Automattic/mongoose/issues/1091
|
4708 | * @see http://docs.mongodb.org/manual/reference/projection/elemMatch/
|
4709 | * @api private
|
4710 | */
|
4711 |
|
4712 | Query.prototype._castFields = function _castFields(fields) {
|
4713 | let selected,
|
4714 | elemMatchKeys,
|
4715 | keys,
|
4716 | key,
|
4717 | out,
|
4718 | i;
|
4719 |
|
4720 | if (fields) {
|
4721 | keys = Object.keys(fields);
|
4722 | elemMatchKeys = [];
|
4723 | i = keys.length;
|
4724 |
|
4725 | // collect $elemMatch args
|
4726 | while (i--) {
|
4727 | key = keys[i];
|
4728 | if (fields[key].$elemMatch) {
|
4729 | selected || (selected = {});
|
4730 | selected[key] = fields[key];
|
4731 | elemMatchKeys.push(key);
|
4732 | }
|
4733 | }
|
4734 | }
|
4735 |
|
4736 | if (selected) {
|
4737 | // they passed $elemMatch, cast em
|
4738 | try {
|
4739 | out = this.cast(this.model, selected);
|
4740 | } catch (err) {
|
4741 | return err;
|
4742 | }
|
4743 |
|
4744 | // apply the casted field args
|
4745 | i = elemMatchKeys.length;
|
4746 | while (i--) {
|
4747 | key = elemMatchKeys[i];
|
4748 | fields[key] = out[key];
|
4749 | }
|
4750 | }
|
4751 |
|
4752 | return fields;
|
4753 | };
|
4754 |
|
4755 | /**
|
4756 | * Applies schematype selected options to this query.
|
4757 | * @api private
|
4758 | */
|
4759 |
|
4760 | Query.prototype._applyPaths = function applyPaths() {
|
4761 | this._fields = this._fields || {};
|
4762 | helpers.applyPaths(this._fields, this.model.schema);
|
4763 |
|
4764 | let _selectPopulatedPaths = true;
|
4765 |
|
4766 | if ('selectPopulatedPaths' in this.model.base.options) {
|
4767 | _selectPopulatedPaths = this.model.base.options.selectPopulatedPaths;
|
4768 | }
|
4769 | if ('selectPopulatedPaths' in this.model.schema.options) {
|
4770 | _selectPopulatedPaths = this.model.schema.options.selectPopulatedPaths;
|
4771 | }
|
4772 |
|
4773 | if (_selectPopulatedPaths) {
|
4774 | selectPopulatedFields(this);
|
4775 | }
|
4776 | };
|
4777 |
|
4778 | /**
|
4779 | * Returns a wrapper around a [mongodb driver cursor](http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html).
|
4780 | * A QueryCursor exposes a Streams3 interface, as well as a `.next()` function.
|
4781 | *
|
4782 | * The `.cursor()` function triggers pre find hooks, but **not** post find hooks.
|
4783 | *
|
4784 | * ####Example
|
4785 | *
|
4786 | * // There are 2 ways to use a cursor. First, as a stream:
|
4787 | * Thing.
|
4788 | * find({ name: /^hello/ }).
|
4789 | * cursor().
|
4790 | * on('data', function(doc) { console.log(doc); }).
|
4791 | * on('end', function() { console.log('Done!'); });
|
4792 | *
|
4793 | * // Or you can use `.next()` to manually get the next doc in the stream.
|
4794 | * // `.next()` returns a promise, so you can use promises or callbacks.
|
4795 | * var cursor = Thing.find({ name: /^hello/ }).cursor();
|
4796 | * cursor.next(function(error, doc) {
|
4797 | * console.log(doc);
|
4798 | * });
|
4799 | *
|
4800 | * // Because `.next()` returns a promise, you can use co
|
4801 | * // to easily iterate through all documents without loading them
|
4802 | * // all into memory.
|
4803 | * co(function*() {
|
4804 | * const cursor = Thing.find({ name: /^hello/ }).cursor();
|
4805 | * for (let doc = yield cursor.next(); doc != null; doc = yield cursor.next()) {
|
4806 | * console.log(doc);
|
4807 | * }
|
4808 | * });
|
4809 | *
|
4810 | * ####Valid options
|
4811 | *
|
4812 | * - `transform`: optional function which accepts a mongoose document. The return value of the function will be emitted on `data` and returned by `.next()`.
|
4813 | *
|
4814 | * @return {QueryCursor}
|
4815 | * @param {Object} [options]
|
4816 | * @see QueryCursor
|
4817 | * @api public
|
4818 | */
|
4819 |
|
4820 | Query.prototype.cursor = function cursor(opts) {
|
4821 | this._applyPaths();
|
4822 | this._fields = this._castFields(this._fields);
|
4823 | this.setOptions({ projection: this._fieldsForExec() });
|
4824 | if (opts) {
|
4825 | this.setOptions(opts);
|
4826 | }
|
4827 |
|
4828 | const options = Object.assign({}, this._optionsForExec(), {
|
4829 | projection: this.projection()
|
4830 | });
|
4831 | try {
|
4832 | this.cast(this.model);
|
4833 | } catch (err) {
|
4834 | return (new QueryCursor(this, options))._markError(err);
|
4835 | }
|
4836 |
|
4837 | return new QueryCursor(this, options);
|
4838 | };
|
4839 |
|
4840 | // the rest of these are basically to support older Mongoose syntax with mquery
|
4841 |
|
4842 | /**
|
4843 | * _DEPRECATED_ Alias of `maxScan`
|
4844 | *
|
4845 | * @deprecated
|
4846 | * @see maxScan #query_Query-maxScan
|
4847 | * @method maxscan
|
4848 | * @memberOf Query
|
4849 | * @instance
|
4850 | */
|
4851 |
|
4852 | Query.prototype.maxscan = Query.base.maxScan;
|
4853 |
|
4854 | /**
|
4855 | * Sets the tailable option (for use with capped collections).
|
4856 | *
|
4857 | * ####Example
|
4858 | *
|
4859 | * query.tailable() // true
|
4860 | * query.tailable(true)
|
4861 | * query.tailable(false)
|
4862 | *
|
4863 | * ####Note
|
4864 | *
|
4865 | * Cannot be used with `distinct()`
|
4866 | *
|
4867 | * @param {Boolean} bool defaults to true
|
4868 | * @param {Object} [opts] options to set
|
4869 | * @param {Number} [opts.numberOfRetries] if cursor is exhausted, retry this many times before giving up
|
4870 | * @param {Number} [opts.tailableRetryInterval] if cursor is exhausted, wait this many milliseconds before retrying
|
4871 | * @see tailable http://docs.mongodb.org/manual/tutorial/create-tailable-cursor/
|
4872 | * @api public
|
4873 | */
|
4874 |
|
4875 | Query.prototype.tailable = function(val, opts) {
|
4876 | // we need to support the tailable({ awaitdata : true }) as well as the
|
4877 | // tailable(true, {awaitdata :true}) syntax that mquery does not support
|
4878 | if (val && val.constructor.name === 'Object') {
|
4879 | opts = val;
|
4880 | val = true;
|
4881 | }
|
4882 |
|
4883 | if (val === undefined) {
|
4884 | val = true;
|
4885 | }
|
4886 |
|
4887 | if (opts && typeof opts === 'object') {
|
4888 | for (const key in opts) {
|
4889 | if (key === 'awaitdata') {
|
4890 | // For backwards compatibility
|
4891 | this.options[key] = !!opts[key];
|
4892 | } else {
|
4893 | this.options[key] = opts[key];
|
4894 | }
|
4895 | }
|
4896 | }
|
4897 |
|
4898 | return Query.base.tailable.call(this, val);
|
4899 | };
|
4900 |
|
4901 | /**
|
4902 | * Declares an intersects query for `geometry()`.
|
4903 | *
|
4904 | * ####Example
|
4905 | *
|
4906 | * query.where('path').intersects().geometry({
|
4907 | * type: 'LineString'
|
4908 | * , coordinates: [[180.0, 11.0], [180, 9.0]]
|
4909 | * })
|
4910 | *
|
4911 | * query.where('path').intersects({
|
4912 | * type: 'LineString'
|
4913 | * , coordinates: [[180.0, 11.0], [180, 9.0]]
|
4914 | * })
|
4915 | *
|
4916 | * ####NOTE:
|
4917 | *
|
4918 | * **MUST** be used after `where()`.
|
4919 | *
|
4920 | * ####NOTE:
|
4921 | *
|
4922 | * In Mongoose 3.7, `intersects` changed from a getter to a function. If you need the old syntax, use [this](https://github.com/ebensing/mongoose-within).
|
4923 | *
|
4924 | * @method intersects
|
4925 | * @memberOf Query
|
4926 | * @instance
|
4927 | * @param {Object} [arg]
|
4928 | * @return {Query} this
|
4929 | * @see $geometry http://docs.mongodb.org/manual/reference/operator/geometry/
|
4930 | * @see geoIntersects http://docs.mongodb.org/manual/reference/operator/geoIntersects/
|
4931 | * @api public
|
4932 | */
|
4933 |
|
4934 | /**
|
4935 | * Specifies a `$geometry` condition
|
4936 | *
|
4937 | * ####Example
|
4938 | *
|
4939 | * var polyA = [[[ 10, 20 ], [ 10, 40 ], [ 30, 40 ], [ 30, 20 ]]]
|
4940 | * query.where('loc').within().geometry({ type: 'Polygon', coordinates: polyA })
|
4941 | *
|
4942 | * // or
|
4943 | * var polyB = [[ 0, 0 ], [ 1, 1 ]]
|
4944 | * query.where('loc').within().geometry({ type: 'LineString', coordinates: polyB })
|
4945 | *
|
4946 | * // or
|
4947 | * var polyC = [ 0, 0 ]
|
4948 | * query.where('loc').within().geometry({ type: 'Point', coordinates: polyC })
|
4949 | *
|
4950 | * // or
|
4951 | * query.where('loc').intersects().geometry({ type: 'Point', coordinates: polyC })
|
4952 | *
|
4953 | * The argument is assigned to the most recent path passed to `where()`.
|
4954 | *
|
4955 | * ####NOTE:
|
4956 | *
|
4957 | * `geometry()` **must** come after either `intersects()` or `within()`.
|
4958 | *
|
4959 | * The `object` argument must contain `type` and `coordinates` properties.
|
4960 | * - type {String}
|
4961 | * - coordinates {Array}
|
4962 | *
|
4963 | * @method geometry
|
4964 | * @memberOf Query
|
4965 | * @instance
|
4966 | * @param {Object} object Must contain a `type` property which is a String and a `coordinates` property which is an Array. See the examples.
|
4967 | * @return {Query} this
|
4968 | * @see $geometry http://docs.mongodb.org/manual/reference/operator/geometry/
|
4969 | * @see http://docs.mongodb.org/manual/release-notes/2.4/#new-geospatial-indexes-with-geojson-and-improved-spherical-geometry
|
4970 | * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing
|
4971 | * @api public
|
4972 | */
|
4973 |
|
4974 | /**
|
4975 | * Specifies a `$near` or `$nearSphere` condition
|
4976 | *
|
4977 | * These operators return documents sorted by distance.
|
4978 | *
|
4979 | * ####Example
|
4980 | *
|
4981 | * query.where('loc').near({ center: [10, 10] });
|
4982 | * query.where('loc').near({ center: [10, 10], maxDistance: 5 });
|
4983 | * query.where('loc').near({ center: [10, 10], maxDistance: 5, spherical: true });
|
4984 | * query.near('loc', { center: [10, 10], maxDistance: 5 });
|
4985 | *
|
4986 | * @method near
|
4987 | * @memberOf Query
|
4988 | * @instance
|
4989 | * @param {String} [path]
|
4990 | * @param {Object} val
|
4991 | * @return {Query} this
|
4992 | * @see $near http://docs.mongodb.org/manual/reference/operator/near/
|
4993 | * @see $nearSphere http://docs.mongodb.org/manual/reference/operator/nearSphere/
|
4994 | * @see $maxDistance http://docs.mongodb.org/manual/reference/operator/maxDistance/
|
4995 | * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing
|
4996 | * @api public
|
4997 | */
|
4998 |
|
4999 | /*!
|
5000 | * Overwriting mquery is needed to support a couple different near() forms found in older
|
5001 | * versions of mongoose
|
5002 | * near([1,1])
|
5003 | * near(1,1)
|
5004 | * near(field, [1,2])
|
5005 | * near(field, 1, 2)
|
5006 | * In addition to all of the normal forms supported by mquery
|
5007 | */
|
5008 |
|
5009 | Query.prototype.near = function() {
|
5010 | const params = [];
|
5011 | const sphere = this._mongooseOptions.nearSphere;
|
5012 |
|
5013 | // TODO refactor
|
5014 |
|
5015 | if (arguments.length === 1) {
|
5016 | if (Array.isArray(arguments[0])) {
|
5017 | params.push({center: arguments[0], spherical: sphere});
|
5018 | } else if (typeof arguments[0] === 'string') {
|
5019 | // just passing a path
|
5020 | params.push(arguments[0]);
|
5021 | } else if (utils.isObject(arguments[0])) {
|
5022 | if (typeof arguments[0].spherical !== 'boolean') {
|
5023 | arguments[0].spherical = sphere;
|
5024 | }
|
5025 | params.push(arguments[0]);
|
5026 | } else {
|
5027 | throw new TypeError('invalid argument');
|
5028 | }
|
5029 | } else if (arguments.length === 2) {
|
5030 | if (typeof arguments[0] === 'number' && typeof arguments[1] === 'number') {
|
5031 | params.push({center: [arguments[0], arguments[1]], spherical: sphere});
|
5032 | } else if (typeof arguments[0] === 'string' && Array.isArray(arguments[1])) {
|
5033 | params.push(arguments[0]);
|
5034 | params.push({center: arguments[1], spherical: sphere});
|
5035 | } else if (typeof arguments[0] === 'string' && utils.isObject(arguments[1])) {
|
5036 | params.push(arguments[0]);
|
5037 | if (typeof arguments[1].spherical !== 'boolean') {
|
5038 | arguments[1].spherical = sphere;
|
5039 | }
|
5040 | params.push(arguments[1]);
|
5041 | } else {
|
5042 | throw new TypeError('invalid argument');
|
5043 | }
|
5044 | } else if (arguments.length === 3) {
|
5045 | if (typeof arguments[0] === 'string' && typeof arguments[1] === 'number'
|
5046 | && typeof arguments[2] === 'number') {
|
5047 | params.push(arguments[0]);
|
5048 | params.push({center: [arguments[1], arguments[2]], spherical: sphere});
|
5049 | } else {
|
5050 | throw new TypeError('invalid argument');
|
5051 | }
|
5052 | } else {
|
5053 | throw new TypeError('invalid argument');
|
5054 | }
|
5055 |
|
5056 | return Query.base.near.apply(this, params);
|
5057 | };
|
5058 |
|
5059 | /**
|
5060 | * _DEPRECATED_ Specifies a `$nearSphere` condition
|
5061 | *
|
5062 | * ####Example
|
5063 | *
|
5064 | * query.where('loc').nearSphere({ center: [10, 10], maxDistance: 5 });
|
5065 | *
|
5066 | * **Deprecated.** Use `query.near()` instead with the `spherical` option set to `true`.
|
5067 | *
|
5068 | * ####Example
|
5069 | *
|
5070 | * query.where('loc').near({ center: [10, 10], spherical: true });
|
5071 | *
|
5072 | * @deprecated
|
5073 | * @see near() #query_Query-near
|
5074 | * @see $near http://docs.mongodb.org/manual/reference/operator/near/
|
5075 | * @see $nearSphere http://docs.mongodb.org/manual/reference/operator/nearSphere/
|
5076 | * @see $maxDistance http://docs.mongodb.org/manual/reference/operator/maxDistance/
|
5077 | */
|
5078 |
|
5079 | Query.prototype.nearSphere = function() {
|
5080 | this._mongooseOptions.nearSphere = true;
|
5081 | this.near.apply(this, arguments);
|
5082 | return this;
|
5083 | };
|
5084 |
|
5085 | /**
|
5086 | * Returns an asyncIterator for use with [`for/await/of` loops](http://bit.ly/async-iterators)
|
5087 | * This function *only* works for `find()` queries.
|
5088 | * You do not need to call this function explicitly, the JavaScript runtime
|
5089 | * will call it for you.
|
5090 | *
|
5091 | * ####Example
|
5092 | *
|
5093 | * for await (const doc of Model.aggregate([{ $sort: { name: 1 } }])) {
|
5094 | * console.log(doc.name);
|
5095 | * }
|
5096 | *
|
5097 | * Node.js 10.x supports async iterators natively without any flags. You can
|
5098 | * enable async iterators in Node.js 8.x using the [`--harmony_async_iteration` flag](https://github.com/tc39/proposal-async-iteration/issues/117#issuecomment-346695187).
|
5099 | *
|
5100 | * **Note:** This function is not if `Symbol.asyncIterator` is undefined. If
|
5101 | * `Symbol.asyncIterator` is undefined, that means your Node.js version does not
|
5102 | * support async iterators.
|
5103 | *
|
5104 | * @method Symbol.asyncIterator
|
5105 | * @memberOf Query
|
5106 | * @instance
|
5107 | * @api public
|
5108 | */
|
5109 |
|
5110 | if (Symbol.asyncIterator != null) {
|
5111 | Query.prototype[Symbol.asyncIterator] = function() {
|
5112 | return this.cursor().transformNull().map(doc => {
|
5113 | return doc == null ? { done: true } : { value: doc, done: false };
|
5114 | });
|
5115 | };
|
5116 | }
|
5117 |
|
5118 | /**
|
5119 | * Specifies a `$polygon` condition
|
5120 | *
|
5121 | * ####Example
|
5122 | *
|
5123 | * query.where('loc').within().polygon([10,20], [13, 25], [7,15])
|
5124 | * query.polygon('loc', [10,20], [13, 25], [7,15])
|
5125 | *
|
5126 | * @method polygon
|
5127 | * @memberOf Query
|
5128 | * @instance
|
5129 | * @param {String|Array} [path]
|
5130 | * @param {Array|Object} [coordinatePairs...]
|
5131 | * @return {Query} this
|
5132 | * @see $polygon http://docs.mongodb.org/manual/reference/operator/polygon/
|
5133 | * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing
|
5134 | * @api public
|
5135 | */
|
5136 |
|
5137 | /**
|
5138 | * Specifies a `$box` condition
|
5139 | *
|
5140 | * ####Example
|
5141 | *
|
5142 | * var lowerLeft = [40.73083, -73.99756]
|
5143 | * var upperRight= [40.741404, -73.988135]
|
5144 | *
|
5145 | * query.where('loc').within().box(lowerLeft, upperRight)
|
5146 | * query.box({ ll : lowerLeft, ur : upperRight })
|
5147 | *
|
5148 | * @method box
|
5149 | * @memberOf Query
|
5150 | * @instance
|
5151 | * @see $box http://docs.mongodb.org/manual/reference/operator/box/
|
5152 | * @see within() Query#within #query_Query-within
|
5153 | * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing
|
5154 | * @param {Object} val
|
5155 | * @param [Array] Upper Right Coords
|
5156 | * @return {Query} this
|
5157 | * @api public
|
5158 | */
|
5159 |
|
5160 | /*!
|
5161 | * this is needed to support the mongoose syntax of:
|
5162 | * box(field, { ll : [x,y], ur : [x2,y2] })
|
5163 | * box({ ll : [x,y], ur : [x2,y2] })
|
5164 | */
|
5165 |
|
5166 | Query.prototype.box = function(ll, ur) {
|
5167 | if (!Array.isArray(ll) && utils.isObject(ll)) {
|
5168 | ur = ll.ur;
|
5169 | ll = ll.ll;
|
5170 | }
|
5171 | return Query.base.box.call(this, ll, ur);
|
5172 | };
|
5173 |
|
5174 | /**
|
5175 | * Specifies a `$center` or `$centerSphere` condition.
|
5176 | *
|
5177 | * ####Example
|
5178 | *
|
5179 | * var area = { center: [50, 50], radius: 10, unique: true }
|
5180 | * query.where('loc').within().circle(area)
|
5181 | * // alternatively
|
5182 | * query.circle('loc', area);
|
5183 | *
|
5184 | * // spherical calculations
|
5185 | * var area = { center: [50, 50], radius: 10, unique: true, spherical: true }
|
5186 | * query.where('loc').within().circle(area)
|
5187 | * // alternatively
|
5188 | * query.circle('loc', area);
|
5189 | *
|
5190 | * @method circle
|
5191 | * @memberOf Query
|
5192 | * @instance
|
5193 | * @param {String} [path]
|
5194 | * @param {Object} area
|
5195 | * @return {Query} this
|
5196 | * @see $center http://docs.mongodb.org/manual/reference/operator/center/
|
5197 | * @see $centerSphere http://docs.mongodb.org/manual/reference/operator/centerSphere/
|
5198 | * @see $geoWithin http://docs.mongodb.org/manual/reference/operator/geoWithin/
|
5199 | * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing
|
5200 | * @api public
|
5201 | */
|
5202 |
|
5203 | /**
|
5204 | * _DEPRECATED_ Alias for [circle](#query_Query-circle)
|
5205 | *
|
5206 | * **Deprecated.** Use [circle](#query_Query-circle) instead.
|
5207 | *
|
5208 | * @deprecated
|
5209 | * @method center
|
5210 | * @memberOf Query
|
5211 | * @instance
|
5212 | * @api public
|
5213 | */
|
5214 |
|
5215 | Query.prototype.center = Query.base.circle;
|
5216 |
|
5217 | /**
|
5218 | * _DEPRECATED_ Specifies a `$centerSphere` condition
|
5219 | *
|
5220 | * **Deprecated.** Use [circle](#query_Query-circle) instead.
|
5221 | *
|
5222 | * ####Example
|
5223 | *
|
5224 | * var area = { center: [50, 50], radius: 10 };
|
5225 | * query.where('loc').within().centerSphere(area);
|
5226 | *
|
5227 | * @deprecated
|
5228 | * @param {String} [path]
|
5229 | * @param {Object} val
|
5230 | * @return {Query} this
|
5231 | * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing
|
5232 | * @see $centerSphere http://docs.mongodb.org/manual/reference/operator/centerSphere/
|
5233 | * @api public
|
5234 | */
|
5235 |
|
5236 | Query.prototype.centerSphere = function() {
|
5237 | if (arguments[0] && arguments[0].constructor.name === 'Object') {
|
5238 | arguments[0].spherical = true;
|
5239 | }
|
5240 |
|
5241 | if (arguments[1] && arguments[1].constructor.name === 'Object') {
|
5242 | arguments[1].spherical = true;
|
5243 | }
|
5244 |
|
5245 | Query.base.circle.apply(this, arguments);
|
5246 | };
|
5247 |
|
5248 | /**
|
5249 | * Determines if field selection has been made.
|
5250 | *
|
5251 | * @method selected
|
5252 | * @memberOf Query
|
5253 | * @instance
|
5254 | * @return {Boolean}
|
5255 | * @api public
|
5256 | */
|
5257 |
|
5258 | /**
|
5259 | * Determines if inclusive field selection has been made.
|
5260 | *
|
5261 | * query.selectedInclusively() // false
|
5262 | * query.select('name')
|
5263 | * query.selectedInclusively() // true
|
5264 | *
|
5265 | * @method selectedInclusively
|
5266 | * @memberOf Query
|
5267 | * @instance
|
5268 | * @return {Boolean}
|
5269 | * @api public
|
5270 | */
|
5271 |
|
5272 | Query.prototype.selectedInclusively = function selectedInclusively() {
|
5273 | return isInclusive(this._fields);
|
5274 | };
|
5275 |
|
5276 | /**
|
5277 | * Determines if exclusive field selection has been made.
|
5278 | *
|
5279 | * query.selectedExclusively() // false
|
5280 | * query.select('-name')
|
5281 | * query.selectedExclusively() // true
|
5282 | * query.selectedInclusively() // false
|
5283 | *
|
5284 | * @method selectedExclusively
|
5285 | * @memberOf Query
|
5286 | * @instance
|
5287 | * @return {Boolean}
|
5288 | * @api public
|
5289 | */
|
5290 |
|
5291 | Query.prototype.selectedExclusively = function selectedExclusively() {
|
5292 | if (!this._fields) {
|
5293 | return false;
|
5294 | }
|
5295 |
|
5296 | const keys = Object.keys(this._fields);
|
5297 | if (keys.length === 0) {
|
5298 | return false;
|
5299 | }
|
5300 |
|
5301 | for (let i = 0; i < keys.length; ++i) {
|
5302 | const key = keys[i];
|
5303 | if (key === '_id') {
|
5304 | continue;
|
5305 | }
|
5306 | if (this._fields[key] === 0 || this._fields[key] === false) {
|
5307 | return true;
|
5308 | }
|
5309 | }
|
5310 |
|
5311 | return false;
|
5312 | };
|
5313 |
|
5314 | /*!
|
5315 | * Export
|
5316 | */
|
5317 |
|
5318 | module.exports = Query;
|