UNPKG

33.7 kBTypeScriptView Raw
1declare module 'mongoose' {
2 import mongodb = require('mongodb');
3
4 export type Condition<T> = T | QuerySelector<T | any> | any;
5
6 /**
7 * Filter query to select the documents that match the query
8 * @example
9 * ```js
10 * { age: { $gte: 30 } }
11 * ```
12 */
13 type FilterQuery<T> = {
14 [P in keyof T]?: Condition<T[P]>;
15 } & RootQuerySelector<T>;
16
17 type MongooseBaseQueryOptionKeys =
18 | 'context'
19 | 'multipleCastError'
20 | 'overwriteDiscriminatorKey'
21 | 'populate'
22 | 'runValidators'
23 | 'sanitizeProjection'
24 | 'sanitizeFilter'
25 | 'setDefaultsOnInsert'
26 | 'strict'
27 | 'strictQuery'
28 | 'translateAliases';
29
30 type MongooseQueryOptions<
31 DocType = unknown,
32 Keys extends keyof QueryOptions<DocType> = MongooseBaseQueryOptionKeys | 'timestamps' | 'lean'
33 > = Pick<QueryOptions<DocType>, Keys> & {
34 [other: string]: any;
35 };
36
37 type MongooseBaseQueryOptions<DocType = unknown> = MongooseQueryOptions<DocType, MongooseBaseQueryOptionKeys>;
38
39 type MongooseUpdateQueryOptions<DocType = unknown> = MongooseQueryOptions<
40 DocType,
41 MongooseBaseQueryOptionKeys | 'timestamps'
42 >;
43
44 type ProjectionFields<DocType> = { [Key in keyof DocType]?: any } & Record<string, any>;
45
46 type QueryWithHelpers<
47 ResultType,
48 DocType,
49 THelpers = {},
50 RawDocType = DocType,
51 QueryOp = 'find',
52 TInstanceMethods = Record<string, never>
53 > = Query<ResultType, DocType, THelpers, RawDocType, QueryOp, TInstanceMethods> & THelpers;
54
55 type QuerySelector<T> = {
56 // Comparison
57 $eq?: T;
58 $gt?: T;
59 $gte?: T;
60 $in?: [T] extends AnyArray<any> ? Unpacked<T>[] : T[];
61 $lt?: T;
62 $lte?: T;
63 $ne?: T;
64 $nin?: [T] extends AnyArray<any> ? Unpacked<T>[] : T[];
65 // Logical
66 $not?: T extends string ? QuerySelector<T> | RegExp : QuerySelector<T>;
67 // Element
68 /**
69 * When `true`, `$exists` matches the documents that contain the field,
70 * including documents where the field value is null.
71 */
72 $exists?: boolean;
73 $type?: string | number;
74 // Evaluation
75 $expr?: any;
76 $jsonSchema?: any;
77 $mod?: T extends number ? [number, number] : never;
78 $regex?: T extends string ? RegExp | string : never;
79 $options?: T extends string ? string : never;
80 // Geospatial
81 // TODO: define better types for geo queries
82 $geoIntersects?: { $geometry: object };
83 $geoWithin?: object;
84 $near?: object;
85 $nearSphere?: object;
86 $maxDistance?: number;
87 // Array
88 // TODO: define better types for $all and $elemMatch
89 $all?: T extends AnyArray<any> ? any[] : never;
90 $elemMatch?: T extends AnyArray<any> ? object : never;
91 $size?: T extends AnyArray<any> ? number : never;
92 // Bitwise
93 $bitsAllClear?: number | mongodb.Binary | number[];
94 $bitsAllSet?: number | mongodb.Binary | number[];
95 $bitsAnyClear?: number | mongodb.Binary | number[];
96 $bitsAnySet?: number | mongodb.Binary | number[];
97 };
98
99 type RootQuerySelector<T> = {
100 /** @see https://www.mongodb.com/docs/manual/reference/operator/query/and/#op._S_and */
101 $and?: Array<FilterQuery<T>>;
102 /** @see https://www.mongodb.com/docs/manual/reference/operator/query/nor/#op._S_nor */
103 $nor?: Array<FilterQuery<T>>;
104 /** @see https://www.mongodb.com/docs/manual/reference/operator/query/or/#op._S_or */
105 $or?: Array<FilterQuery<T>>;
106 /** @see https://www.mongodb.com/docs/manual/reference/operator/query/text */
107 $text?: {
108 $search: string;
109 $language?: string;
110 $caseSensitive?: boolean;
111 $diacriticSensitive?: boolean;
112 };
113 /** @see https://www.mongodb.com/docs/manual/reference/operator/query/where/#op._S_where */
114 $where?: string | Function;
115 /** @see https://www.mongodb.com/docs/manual/reference/operator/query/comment/#op._S_comment */
116 $comment?: string;
117 // we could not find a proper TypeScript generic to support nested queries e.g. 'user.friends.name'
118 // this will mark all unrecognized properties as any (including nested queries)
119 [key: string]: any;
120 };
121
122 interface QueryTimestampsConfig {
123 createdAt?: boolean;
124 updatedAt?: boolean;
125 }
126
127 interface QueryOptions<DocType = unknown> extends
128 PopulateOption,
129 SessionOption {
130 arrayFilters?: { [key: string]: any }[];
131 batchSize?: number;
132 collation?: mongodb.CollationOptions;
133 comment?: any;
134 context?: string;
135 explain?: mongodb.ExplainVerbosityLike;
136 fields?: any | string;
137 hint?: mongodb.Hint;
138 /**
139 * If truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document.
140 */
141 lean?: boolean | Record<string, any>;
142 limit?: number;
143 maxTimeMS?: number;
144 multi?: boolean;
145 multipleCastError?: boolean;
146 /**
147 * By default, `findOneAndUpdate()` returns the document as it was **before**
148 * `update` was applied. If you set `new: true`, `findOneAndUpdate()` will
149 * instead give you the object after `update` was applied.
150 */
151 new?: boolean;
152
153 overwriteDiscriminatorKey?: boolean;
154 projection?: ProjectionType<DocType>;
155 /**
156 * if true, returns the full ModifyResult rather than just the document
157 */
158 includeResultMetadata?: boolean;
159 readPreference?: string | mongodb.ReadPreferenceMode;
160 /**
161 * An alias for the `new` option. `returnOriginal: false` is equivalent to `new: true`.
162 */
163 returnOriginal?: boolean;
164 /**
165 * Another alias for the `new` option. `returnOriginal` is deprecated so this should be used.
166 */
167 returnDocument?: 'before' | 'after';
168 /**
169 * Set to true to enable `update validators`
170 * (https://mongoosejs.com/docs/validation.html#update-validators). Defaults to false.
171 */
172 runValidators?: boolean;
173 /* Set to `true` to automatically sanitize potentially unsafe user-generated query projections */
174 sanitizeProjection?: boolean;
175 /**
176 * Set to `true` to automatically sanitize potentially unsafe query filters by stripping out query selectors that
177 * aren't explicitly allowed using `mongoose.trusted()`.
178 */
179 sanitizeFilter?: boolean;
180 setDefaultsOnInsert?: boolean;
181 skip?: number;
182 sort?: any;
183 /** overwrites the schema's strict mode option */
184 strict?: boolean | string;
185 /**
186 * equal to `strict` by default, may be `false`, `true`, or `'throw'`. Sets the default
187 * [strictQuery](https://mongoosejs.com/docs/guide.html#strictQuery) mode for schemas.
188 */
189 strictQuery?: boolean | 'throw';
190 tailable?: number;
191 /**
192 * If set to `false` and schema-level timestamps are enabled,
193 * skip timestamps for this update. Note that this allows you to overwrite
194 * timestamps. Does nothing if schema-level timestamps are not set.
195 */
196 timestamps?: boolean | QueryTimestampsConfig;
197 /**
198 * If `true`, convert any aliases in filter, projection, update, and distinct
199 * to their database property names. Defaults to false.
200 */
201 translateAliases?: boolean;
202 upsert?: boolean;
203 useBigInt64?: boolean;
204 writeConcern?: mongodb.WriteConcern;
205
206 [other: string]: any;
207 }
208
209 type QueryOpThatReturnsDocument = 'find' | 'findOne' | 'findOneAndUpdate' | 'findOneAndReplace' | 'findOneAndDelete';
210
211 type GetLeanResultType<RawDocType, ResultType, QueryOp> = QueryOp extends QueryOpThatReturnsDocument
212 ? (ResultType extends any[] ? Require_id<FlattenMaps<RawDocType>>[] : Require_id<FlattenMaps<RawDocType>>)
213 : ResultType;
214
215 type MergePopulatePaths<RawDocType, ResultType, QueryOp, Paths, TQueryHelpers, TInstanceMethods = Record<string, never>> = QueryOp extends QueryOpThatReturnsDocument
216 ? ResultType extends null
217 ? ResultType
218 : ResultType extends (infer U)[]
219 ? U extends Document
220 ? HydratedDocument<MergeType<RawDocType, Paths>, TInstanceMethods, TQueryHelpers>[]
221 : (MergeType<U, Paths>)[]
222 : ResultType extends Document
223 ? HydratedDocument<MergeType<RawDocType, Paths>, TInstanceMethods, TQueryHelpers>
224 : MergeType<ResultType, Paths>
225 : MergeType<ResultType, Paths>;
226
227 class Query<ResultType, DocType, THelpers = {}, RawDocType = DocType, QueryOp = 'find', TInstanceMethods = Record<string, never>> implements SessionOperation {
228 _mongooseOptions: MongooseQueryOptions<DocType>;
229
230 /**
231 * Returns a wrapper around a [mongodb driver cursor](https://mongodb.github.io/node-mongodb-native/4.9/classes/FindCursor.html).
232 * A QueryCursor exposes a Streams3 interface, as well as a `.next()` function.
233 * This is equivalent to calling `.cursor()` with no arguments.
234 */
235 [Symbol.asyncIterator](): AsyncIterableIterator<Unpacked<ResultType>>;
236
237 /** Executes the query */
238 exec(): Promise<ResultType>;
239
240 $where(argument: string | Function): QueryWithHelpers<
241 DocType[],
242 DocType,
243 THelpers,
244 RawDocType,
245 QueryOp,
246 TInstanceMethods
247 >;
248
249 /** Specifies an `$all` query condition. When called with one argument, the most recent path passed to `where()` is used. */
250 all(path: string, val: Array<any>): this;
251 all(val: Array<any>): this;
252
253 /** Sets the allowDiskUse option for the query (ignored for < 4.4.0) */
254 allowDiskUse(value: boolean): this;
255
256 /** Specifies arguments for an `$and` condition. */
257 and(array: FilterQuery<RawDocType>[]): this;
258
259 /** Specifies the batchSize option. */
260 batchSize(val: number): this;
261
262 /** Specifies a `$box` condition */
263 box(lower: number[], upper: number[]): this;
264 box(val: any): this;
265
266 /**
267 * Casts this query to the schema of `model`.
268 *
269 * @param {Model} [model] the model to cast to. If not set, defaults to `this.model`
270 * @param {Object} [obj] If not set, defaults to this query's conditions
271 * @return {Object} the casted `obj`
272 */
273 cast(model?: Model<any, THelpers> | null, obj?: any): any;
274
275 /**
276 * Executes the query returning a `Promise` which will be
277 * resolved with either the doc(s) or rejected with the error.
278 * Like `.then()`, but only takes a rejection handler.
279 */
280 catch: Promise<ResultType>['catch'];
281
282 /**
283 * Executes the query returning a `Promise` which will be
284 * resolved with `.finally()` chained.
285 */
286 finally: Promise<ResultType>['finally'];
287
288 // Returns a string representation of this query.
289 [Symbol.toStringTag]: string;
290
291 /** Specifies a `$center` or `$centerSphere` condition. */
292 circle(path: string, area: any): this;
293 circle(area: any): this;
294
295 /** Make a copy of this query so you can re-execute it. */
296 clone(): this;
297
298 /** Adds a collation to this op (MongoDB 3.4 and up) */
299 collation(value: mongodb.CollationOptions): this;
300
301 /** Specifies the `comment` option. */
302 comment(val: string): this;
303
304 /** Specifies this query as a `countDocuments` query. */
305 countDocuments(
306 criteria?: FilterQuery<RawDocType>,
307 options?: QueryOptions<DocType>
308 ): QueryWithHelpers<number, DocType, THelpers, RawDocType, 'countDocuments', TInstanceMethods>;
309
310 /**
311 * Returns a wrapper around a [mongodb driver cursor](https://mongodb.github.io/node-mongodb-native/4.9/classes/FindCursor.html).
312 * A QueryCursor exposes a Streams3 interface, as well as a `.next()` function.
313 */
314 cursor(options?: QueryOptions<DocType>): Cursor<Unpacked<ResultType>, QueryOptions<DocType>>;
315
316 /**
317 * Declare and/or execute this query as a `deleteMany()` operation. Works like
318 * remove, except it deletes _every_ document that matches `filter` in the
319 * collection, regardless of the value of `single`.
320 */
321 deleteMany(
322 filter?: FilterQuery<RawDocType>,
323 options?: QueryOptions<DocType>
324 ): QueryWithHelpers<any, DocType, THelpers, RawDocType, 'deleteMany', TInstanceMethods>;
325 deleteMany(filter: FilterQuery<RawDocType>): QueryWithHelpers<
326 any,
327 DocType,
328 THelpers,
329 RawDocType,
330 'deleteMany',
331 TInstanceMethods
332 >;
333 deleteMany(): QueryWithHelpers<any, DocType, THelpers, RawDocType, 'deleteMany', TInstanceMethods>;
334
335 /**
336 * Declare and/or execute this query as a `deleteOne()` operation. Works like
337 * remove, except it deletes at most one document regardless of the `single`
338 * option.
339 */
340 deleteOne(
341 filter?: FilterQuery<RawDocType>,
342 options?: QueryOptions<DocType>
343 ): QueryWithHelpers<any, DocType, THelpers, RawDocType, 'deleteOne', TInstanceMethods>;
344 deleteOne(filter: FilterQuery<RawDocType>): QueryWithHelpers<
345 any,
346 DocType,
347 THelpers,
348 RawDocType,
349 'deleteOne',
350 TInstanceMethods
351 >;
352 deleteOne(): QueryWithHelpers<any, DocType, THelpers, RawDocType, 'deleteOne', TInstanceMethods>;
353
354 /** Creates a `distinct` query: returns the distinct values of the given `field` that match `filter`. */
355 distinct<DocKey extends string, ResultType = unknown>(
356 field: DocKey,
357 filter?: FilterQuery<RawDocType>
358 ): QueryWithHelpers<
359 Array<
360 DocKey extends keyof WithLevel1NestedPaths<DocType>
361 ? WithoutUndefined<Unpacked<WithLevel1NestedPaths<DocType>[DocKey]>>
362 : ResultType
363 >,
364 DocType,
365 THelpers,
366 RawDocType,
367 'distinct',
368 TInstanceMethods
369 >;
370
371 /** Specifies a `$elemMatch` query condition. When called with one argument, the most recent path passed to `where()` is used. */
372 elemMatch<K = string>(path: K, val: any): this;
373 elemMatch(val: Function | any): this;
374
375 /**
376 * Gets/sets the error flag on this query. If this flag is not null or
377 * undefined, the `exec()` promise will reject without executing.
378 */
379 error(): NativeError | null;
380 error(val: NativeError | null): this;
381
382 /** Specifies the complementary comparison value for paths specified with `where()` */
383 equals(val: any): this;
384
385 /** Creates a `estimatedDocumentCount` query: counts the number of documents in the collection. */
386 estimatedDocumentCount(options?: QueryOptions<DocType>): QueryWithHelpers<
387 number,
388 DocType,
389 THelpers,
390 RawDocType,
391 'estimatedDocumentCount',
392 TInstanceMethods
393 >;
394
395 /** Specifies a `$exists` query condition. When called with one argument, the most recent path passed to `where()` is used. */
396 exists<K = string>(path: K, val: boolean): this;
397 exists(val: boolean): this;
398
399 /**
400 * Sets the [`explain` option](https://www.mongodb.com/docs/manual/reference/method/cursor.explain/),
401 * which makes this query return detailed execution stats instead of the actual
402 * query result. This method is useful for determining what index your queries
403 * use.
404 */
405 explain(verbose?: mongodb.ExplainVerbosityLike): this;
406
407 /** Creates a `find` query: gets a list of documents that match `filter`. */
408 find(
409 filter: FilterQuery<RawDocType>,
410 projection?: ProjectionType<RawDocType> | null,
411 options?: QueryOptions<DocType> | null
412 ): QueryWithHelpers<Array<DocType>, DocType, THelpers, RawDocType, 'find', TInstanceMethods>;
413 find(
414 filter: FilterQuery<RawDocType>,
415 projection?: ProjectionType<RawDocType> | null
416 ): QueryWithHelpers<Array<DocType>, DocType, THelpers, RawDocType, 'find', TInstanceMethods>;
417 find(
418 filter: FilterQuery<RawDocType>
419 ): QueryWithHelpers<Array<DocType>, DocType, THelpers, RawDocType, 'find', TInstanceMethods>;
420 find(): QueryWithHelpers<Array<DocType>, DocType, THelpers, RawDocType, 'find', TInstanceMethods>;
421
422 /** Declares the query a findOne operation. When executed, returns the first found document. */
423 findOne(
424 filter?: FilterQuery<RawDocType>,
425 projection?: ProjectionType<RawDocType> | null,
426 options?: QueryOptions<DocType> | null
427 ): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType, 'findOne', TInstanceMethods>;
428 findOne(
429 filter?: FilterQuery<RawDocType>,
430 projection?: ProjectionType<RawDocType> | null
431 ): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType, 'findOne', TInstanceMethods>;
432 findOne(
433 filter?: FilterQuery<RawDocType>
434 ): QueryWithHelpers<DocType | null, RawDocType, THelpers, RawDocType, 'findOne', TInstanceMethods>;
435
436 /** Creates a `findOneAndDelete` query: atomically finds the given document, deletes it, and returns the document as it was before deletion. */
437 findOneAndDelete(
438 filter?: FilterQuery<RawDocType>,
439 options?: QueryOptions<DocType> | null
440 ): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType, 'findOneAndDelete'>;
441
442 /** Creates a `findOneAndUpdate` query: atomically find the first document that matches `filter` and apply `update`. */
443 findOneAndUpdate(
444 filter: FilterQuery<RawDocType>,
445 update: UpdateQuery<RawDocType>,
446 options: QueryOptions<DocType> & { includeResultMetadata: true }
447 ): QueryWithHelpers<ModifyResult<DocType>, DocType, THelpers, RawDocType, 'findOneAndUpdate', TInstanceMethods>;
448 findOneAndUpdate(
449 filter: FilterQuery<RawDocType>,
450 update: UpdateQuery<RawDocType>,
451 options: QueryOptions<DocType> & { upsert: true } & ReturnsNewDoc
452 ): QueryWithHelpers<DocType, DocType, THelpers, RawDocType, 'findOneAndUpdate', TInstanceMethods>;
453 findOneAndUpdate(
454 filter?: FilterQuery<RawDocType>,
455 update?: UpdateQuery<RawDocType>,
456 options?: QueryOptions<DocType> | null
457 ): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType, 'findOneAndUpdate', TInstanceMethods>;
458
459 /** Declares the query a findById operation. When executed, returns the document with the given `_id`. */
460 findById(
461 id: mongodb.ObjectId | any,
462 projection?: ProjectionType<RawDocType> | null,
463 options?: QueryOptions<DocType> | null
464 ): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType, 'findOne', TInstanceMethods>;
465 findById(
466 id: mongodb.ObjectId | any,
467 projection?: ProjectionType<RawDocType> | null
468 ): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType, 'findOne', TInstanceMethods>;
469 findById(
470 id: mongodb.ObjectId | any
471 ): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType, 'findOne', TInstanceMethods>;
472
473 /** Creates a `findByIdAndDelete` query, filtering by the given `_id`. */
474 findByIdAndDelete(
475 id: mongodb.ObjectId | any,
476 options: QueryOptions<DocType> & { includeResultMetadata: true }
477 ): QueryWithHelpers<ModifyResult<DocType>, DocType, THelpers, RawDocType, 'findOneAndDelete', TInstanceMethods>;
478 findByIdAndDelete(
479 id?: mongodb.ObjectId | any,
480 options?: QueryOptions<DocType> | null
481 ): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType, 'findOneAndDelete', TInstanceMethods>;
482
483 /** Creates a `findOneAndUpdate` query, filtering by the given `_id`. */
484 findByIdAndUpdate(
485 id: mongodb.ObjectId | any,
486 update: UpdateQuery<RawDocType>,
487 options: QueryOptions<DocType> & { includeResultMetadata: true }
488 ): QueryWithHelpers<any, DocType, THelpers, RawDocType, 'findOneAndUpdate', TInstanceMethods>;
489 findByIdAndUpdate(
490 id: mongodb.ObjectId | any,
491 update: UpdateQuery<RawDocType>,
492 options: QueryOptions<DocType> & { upsert: true } & ReturnsNewDoc
493 ): QueryWithHelpers<DocType, DocType, THelpers, RawDocType, 'findOneAndUpdate', TInstanceMethods>;
494 findByIdAndUpdate(
495 id?: mongodb.ObjectId | any,
496 update?: UpdateQuery<RawDocType>,
497 options?: QueryOptions<DocType> | null
498 ): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType, 'findOneAndUpdate', TInstanceMethods>;
499 findByIdAndUpdate(
500 id: mongodb.ObjectId | any,
501 update: UpdateQuery<RawDocType>
502 ): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType, 'findOneAndUpdate', TInstanceMethods>;
503
504 /** Specifies a `$geometry` condition */
505 geometry(object: { type: string, coordinates: any[] }): this;
506
507 /**
508 * For update operations, returns the value of a path in the update's `$set`.
509 * Useful for writing getters/setters that can work with both update operations
510 * and `save()`.
511 */
512 get(path: string): any;
513
514 /** Returns the current query filter (also known as conditions) as a POJO. */
515 getFilter(): FilterQuery<RawDocType>;
516
517 /** Gets query options. */
518 getOptions(): QueryOptions<DocType>;
519
520 /** Gets a list of paths to be populated by this query */
521 getPopulatedPaths(): Array<string>;
522
523 /** Returns the current query filter. Equivalent to `getFilter()`. */
524 getQuery(): FilterQuery<RawDocType>;
525
526 /** Returns the current update operations as a JSON object. */
527 getUpdate(): UpdateQuery<DocType> | UpdateWithAggregationPipeline | null;
528
529 /** Specifies a `$gt` query condition. When called with one argument, the most recent path passed to `where()` is used. */
530 gt<K = string>(path: K, val: any): this;
531 gt(val: number): this;
532
533 /** Specifies a `$gte` query condition. When called with one argument, the most recent path passed to `where()` is used. */
534 gte<K = string>(path: K, val: any): this;
535 gte(val: number): this;
536
537 /** Sets query hints. */
538 hint(val: any): this;
539
540 /** Specifies an `$in` query condition. When called with one argument, the most recent path passed to `where()` is used. */
541 in<K = string>(path: K, val: any[]): this;
542 in(val: Array<any>): this;
543
544 /** Declares an intersects query for `geometry()`. */
545 intersects(arg?: any): this;
546
547 /** Requests acknowledgement that this operation has been persisted to MongoDB's on-disk journal. */
548 j(val: boolean | null): this;
549
550 /** Sets the lean option. */
551 lean<
552 LeanResultType = GetLeanResultType<RawDocType, ResultType, QueryOp>
553 >(
554 val?: boolean | any
555 ): QueryWithHelpers<
556 ResultType extends null
557 ? LeanResultType | null
558 : LeanResultType,
559 DocType,
560 THelpers,
561 RawDocType,
562 QueryOp,
563 TInstanceMethods
564 >;
565
566 /** Specifies the maximum number of documents the query will return. */
567 limit(val: number): this;
568
569 /** Specifies a `$lt` query condition. When called with one argument, the most recent path passed to `where()` is used. */
570 lt<K = string>(path: K, val: any): this;
571 lt(val: number): this;
572
573 /** Specifies a `$lte` query condition. When called with one argument, the most recent path passed to `where()` is used. */
574 lte<K = string>(path: K, val: any): this;
575 lte(val: number): this;
576
577 /**
578 * Runs a function `fn` and treats the return value of `fn` as the new value
579 * for the query to resolve to.
580 */
581 transform<MappedType>(fn: (doc: ResultType) => MappedType): QueryWithHelpers<MappedType, DocType, THelpers, RawDocType, QueryOp, TInstanceMethods>;
582
583 /** Specifies an `$maxDistance` query condition. When called with one argument, the most recent path passed to `where()` is used. */
584 maxDistance(path: string, val: number): this;
585 maxDistance(val: number): this;
586
587 /**
588 * Sets the [maxTimeMS](https://www.mongodb.com/docs/manual/reference/method/cursor.maxTimeMS/)
589 * option. This will tell the MongoDB server to abort if the query or write op
590 * has been running for more than `ms` milliseconds.
591 */
592 maxTimeMS(ms: number): this;
593
594 /** Merges another Query or conditions object into this one. */
595 merge(source: Query<any, any> | FilterQuery<RawDocType>): this;
596
597 /** Specifies a `$mod` condition, filters documents for documents whose `path` property is a number that is equal to `remainder` modulo `divisor`. */
598 mod<K = string>(path: K, val: number): this;
599 mod(val: Array<number>): this;
600
601 /** The model this query was created from */
602 model: Model<any>; // Can't use DocType, causes "Type instantiation is excessively deep"
603
604 /**
605 * Getter/setter around the current mongoose-specific options for this query
606 * Below are the current Mongoose-specific options.
607 */
608 mongooseOptions(val?: MongooseQueryOptions): MongooseQueryOptions;
609
610 /** Specifies a `$ne` query condition. When called with one argument, the most recent path passed to `where()` is used. */
611 ne<K = string>(path: K, val: any): this;
612 ne(val: any): this;
613
614 /** Specifies a `$near` or `$nearSphere` condition */
615 near<K = string>(path: K, val: any): this;
616 near(val: any): this;
617
618 /** Specifies an `$nin` query condition. When called with one argument, the most recent path passed to `where()` is used. */
619 nin<K = string>(path: K, val: any[]): this;
620 nin(val: Array<any>): this;
621
622 /** Specifies arguments for an `$nor` condition. */
623 nor(array: Array<FilterQuery<RawDocType>>): this;
624
625 /** Specifies arguments for an `$or` condition. */
626 or(array: Array<FilterQuery<RawDocType>>): this;
627
628 /**
629 * Make this query throw an error if no documents match the given `filter`.
630 * This is handy for integrating with async/await, because `orFail()` saves you
631 * an extra `if` statement to check if no document was found.
632 */
633 orFail(err?: NativeError | (() => NativeError)): QueryWithHelpers<NonNullable<ResultType>, DocType, THelpers, RawDocType, QueryOp, TInstanceMethods>;
634
635 /** Specifies a `$polygon` condition */
636 polygon(path: string, ...coordinatePairs: number[][]): this;
637 polygon(...coordinatePairs: number[][]): this;
638
639 /** Specifies paths which should be populated with other documents. */
640 populate(
641 path: string | string[],
642 select?: string | any,
643 model?: string | Model<any, THelpers>,
644 match?: any
645 ): QueryWithHelpers<
646 ResultType,
647 DocType,
648 THelpers,
649 RawDocType,
650 QueryOp,
651 TInstanceMethods
652 >;
653 populate(
654 options: PopulateOptions | (PopulateOptions | string)[]
655 ): QueryWithHelpers<
656 ResultType,
657 DocType,
658 THelpers,
659 RawDocType,
660 QueryOp,
661 TInstanceMethods
662 >;
663 populate<Paths>(
664 path: string | string[],
665 select?: string | any,
666 model?: string | Model<any, THelpers>,
667 match?: any
668 ): QueryWithHelpers<
669 MergePopulatePaths<RawDocType, ResultType, QueryOp, Paths, THelpers, TInstanceMethods>,
670 DocType,
671 THelpers,
672 UnpackedIntersection<RawDocType, Paths>,
673 QueryOp,
674 TInstanceMethods
675 >;
676 populate<Paths>(
677 options: PopulateOptions | (PopulateOptions | string)[]
678 ): QueryWithHelpers<
679 MergePopulatePaths<RawDocType, ResultType, QueryOp, Paths, THelpers, TInstanceMethods>,
680 DocType,
681 THelpers,
682 UnpackedIntersection<RawDocType, Paths>,
683 QueryOp,
684 TInstanceMethods
685 >;
686
687 /** Add pre middleware to this query instance. Doesn't affect other queries. */
688 pre(fn: Function): this;
689
690 /** Add post middleware to this query instance. Doesn't affect other queries. */
691 post(fn: Function): this;
692
693 /** Get/set the current projection (AKA fields). Pass `null` to remove the current projection. */
694 projection(fields?: ProjectionFields<DocType> | string): ProjectionFields<DocType>;
695 projection(fields: null): null;
696 projection(): ProjectionFields<DocType> | null;
697
698 /** Determines the MongoDB nodes from which to read. */
699 read(mode: string | mongodb.ReadPreferenceMode, tags?: any[]): this;
700
701 /** Sets the readConcern option for the query. */
702 readConcern(level: string): this;
703
704 /** Specifies a `$regex` query condition. When called with one argument, the most recent path passed to `where()` is used. */
705 regex<K = string>(path: K, val: RegExp): this;
706 regex(val: string | RegExp): this;
707
708 /**
709 * Declare and/or execute this query as a replaceOne() operation. Same as
710 * `update()`, except MongoDB will replace the existing document and will
711 * not accept any [atomic](https://www.mongodb.com/docs/manual/tutorial/model-data-for-atomic-operations/#pattern) operators (`$set`, etc.)
712 */
713 replaceOne(
714 filter?: FilterQuery<RawDocType>,
715 replacement?: DocType | AnyObject,
716 options?: QueryOptions<DocType> | null
717 ): QueryWithHelpers<any, DocType, THelpers, RawDocType, 'replaceOne', TInstanceMethods>;
718
719 /**
720 * Sets this query's `sanitizeProjection` option. With `sanitizeProjection()`, you can pass potentially untrusted user data to `.select()`.
721 */
722 sanitizeProjection(value: boolean): this;
723
724 /** Specifies which document fields to include or exclude (also known as the query "projection") */
725 select<RawDocTypeOverride extends { [P in keyof RawDocType]?: any } = {}>(
726 arg: string | string[] | Record<string, number | boolean | string | object>
727 ): QueryWithHelpers<
728 IfEquals<
729 RawDocTypeOverride,
730 {},
731 ResultType,
732 ResultType extends any[]
733 ? ResultType extends HydratedDocument<any>[]
734 ? HydratedDocument<RawDocTypeOverride>[]
735 : RawDocTypeOverride[]
736 : (ResultType extends HydratedDocument<any>
737 ? HydratedDocument<RawDocTypeOverride>
738 : RawDocTypeOverride) | (null extends ResultType ? null : never)
739 >,
740 DocType,
741 THelpers,
742 IfEquals<
743 RawDocTypeOverride,
744 {},
745 RawDocType,
746 RawDocTypeOverride
747 >,
748 QueryOp,
749 TInstanceMethods
750 >;
751
752 /** Determines if field selection has been made. */
753 selected(): boolean;
754
755 /** Determines if exclusive field selection has been made. */
756 selectedExclusively(): boolean;
757
758 /** Determines if inclusive field selection has been made. */
759 selectedInclusively(): boolean;
760
761 /**
762 * Sets the [MongoDB session](https://www.mongodb.com/docs/manual/reference/server-sessions/)
763 * associated with this query. Sessions are how you mark a query as part of a
764 * [transaction](/docs/transactions.html).
765 */
766 session(session: mongodb.ClientSession | null): this;
767
768 /**
769 * Adds a `$set` to this query's update without changing the operation.
770 * This is useful for query middleware so you can add an update regardless
771 * of whether you use `updateOne()`, `updateMany()`, `findOneAndUpdate()`, etc.
772 */
773 set(path: string | Record<string, unknown>, value?: any): this;
774
775 /** Sets query options. Some options only make sense for certain operations. */
776 setOptions(options: QueryOptions<DocType>, overwrite?: boolean): this;
777
778 /** Sets the query conditions to the provided JSON object. */
779 setQuery(val: FilterQuery<RawDocType> | null): void;
780
781 setUpdate(update: UpdateQuery<RawDocType> | UpdateWithAggregationPipeline): void;
782
783 /** Specifies an `$size` query condition. When called with one argument, the most recent path passed to `where()` is used. */
784 size<K = string>(path: K, val: number): this;
785 size(val: number): this;
786
787 /** Specifies the number of documents to skip. */
788 skip(val: number): this;
789
790 /** Specifies a `$slice` projection for an array. */
791 slice(path: string, val: number | Array<number>): this;
792 slice(val: number | Array<number>): this;
793
794 /** Sets the sort order. If an object is passed, values allowed are `asc`, `desc`, `ascending`, `descending`, `1`, and `-1`. */
795 sort(
796 arg?: string | { [key: string]: SortOrder | { $meta: any } } | [string, SortOrder][] | undefined | null,
797 options?: { override?: boolean }
798 ): this;
799
800 /** Sets the tailable option (for use with capped collections). */
801 tailable(bool?: boolean, opts?: {
802 numberOfRetries?: number;
803 tailableRetryInterval?: number;
804 }): this;
805
806 /**
807 * Executes the query returning a `Promise` which will be
808 * resolved with either the doc(s) or rejected with the error.
809 */
810 then: Promise<ResultType>['then'];
811
812 /** Converts this query to a customized, reusable query constructor with all arguments and options retained. */
813 toConstructor<RetType = typeof Query>(): RetType;
814
815 /**
816 * Declare and/or execute this query as an updateMany() operation. Same as
817 * `update()`, except MongoDB will update _all_ documents that match
818 * `filter` (as opposed to just the first one) regardless of the value of
819 * the `multi` option.
820 */
821 updateMany(
822 filter?: FilterQuery<RawDocType>,
823 update?: UpdateQuery<RawDocType> | UpdateWithAggregationPipeline,
824 options?: QueryOptions<DocType> | null
825 ): QueryWithHelpers<UpdateWriteOpResult, DocType, THelpers, RawDocType, 'updateMany', TInstanceMethods>;
826
827 /**
828 * Declare and/or execute this query as an updateOne() operation. Same as
829 * `update()`, except it does not support the `multi` or `overwrite` options.
830 */
831 updateOne(
832 filter?: FilterQuery<RawDocType>,
833 update?: UpdateQuery<RawDocType> | UpdateWithAggregationPipeline,
834 options?: QueryOptions<DocType> | null
835 ): QueryWithHelpers<UpdateWriteOpResult, DocType, THelpers, RawDocType, 'updateOne', TInstanceMethods>;
836
837 /**
838 * Sets the specified number of `mongod` servers, or tag set of `mongod` servers,
839 * that must acknowledge this write before this write is considered successful.
840 */
841 w(val: string | number | null): this;
842
843 /** Specifies a path for use with chaining. */
844 where(path: string, val?: any): this;
845 where(obj: object): this;
846 where(): this;
847
848 /** Defines a `$within` or `$geoWithin` argument for geo-spatial queries. */
849 within(val?: any): this;
850
851 /**
852 * If [`w > 1`](/docs/api/query.html#query_Query-w), the maximum amount of time to
853 * wait for this write to propagate through the replica set before this
854 * operation fails. The default is `0`, which means no timeout.
855 */
856 wtimeout(ms: number): this;
857 }
858}
859
\No newline at end of file