UNPKG

126 kBTypeScriptView Raw
1// Type definitions for MongoDB 3.6
2// Project: https://github.com/mongodb/node-mongodb-native
3// https://github.com/mongodb/node-mongodb-native/tree/3.1
4// Definitions by: Federico Caselli <https://github.com/CaselIT>
5// Alan Marcell <https://github.com/alanmarcell>
6// Gaurav Lahoti <https://github.com/dante-101>
7// Mariano Cortesi <https://github.com/mcortesi>
8// Enrico Picci <https://github.com/EnricoPicci>
9// Alexander Christie <https://github.com/AJCStriker>
10// Julien Chaumond <https://github.com/julien-c>
11// Dan Aprahamian <https://github.com/daprahamian>
12// Denys Bushulyak <https://github.com/denys-bushulyak>
13// Bastien Arata <https://github.com/BastienAr>
14// Wan Bachtiar <https://github.com/sindbach>
15// Geraldine Lemeur <https://github.com/geraldinelemeur>
16// Dominik Heigl <https://github.com/various89>
17// Angela-1 <https://github.com/angela-1>
18// Hector Ribes <https://github.com/hector7>
19// Florian Richter <https://github.com/floric>
20// Erik Christensen <https://github.com/erikc5000>
21// Nick Zahn <https://github.com/Manc>
22// Jarom Loveridge <https://github.com/jloveridge>
23// Luis Pais <https://github.com/ranguna>
24// Hossein Saniei <https://github.com/HosseinAgha>
25// Alberto Silva <https://github.com/albertossilva>
26// Piotr Błażejewicz <https://github.com/peterblazejewicz>
27// Linus Unnebäck <https://github.com/LinusU>
28// Richard Bateman <https://github.com/taxilian>
29// Igor Strebezhev <https://github.com/xamgore>
30// Valentin Agachi <https://github.com/avaly>
31// HitkoDev <https://github.com/HitkoDev>
32// TJT <https://github.com/Celend>
33// Julien TASSIN <https://github.com/jtassin>
34// Anna Henningsen <https://github.com/addaleax>
35// Emmanuel Gautier <https://github.com/emmanuelgautier>
36// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
37// Minimum TypeScript Version: 3.2
38
39// Documentation: https://mongodb.github.io/node-mongodb-native/3.1/api/
40
41/// <reference types="node" />
42/// <reference lib="esnext.asynciterable" />
43
44import { Binary, Decimal128, Double, Int32, Long, ObjectId, Timestamp } from 'bson';
45import { EventEmitter } from 'events';
46import { Readable, Writable } from 'stream';
47import { checkServerIdentity } from 'tls';
48
49type FlattenIfArray<T> = T extends ReadonlyArray<infer R> ? R : T;
50
51export function connect(uri: string, options?: MongoClientOptions): Promise<MongoClient>;
52export function connect(uri: string, callback: MongoCallback<MongoClient>): void;
53export function connect(uri: string, options: MongoClientOptions, callback: MongoCallback<MongoClient>): void;
54
55export { Binary, DBRef, Decimal128, Double, Int32, Long, MaxKey, MinKey, ObjectID, ObjectId, Timestamp } from 'bson';
56
57type NumericTypes = number | Decimal128 | Double | Int32 | Long;
58
59// Class documentation : http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html
60export class MongoClient extends EventEmitter {
61 constructor(uri: string, options?: MongoClientOptions);
62 /** http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html#.connect */
63 static connect(uri: string, callback: MongoCallback<MongoClient>): void;
64 static connect(uri: string, options?: MongoClientOptions): Promise<MongoClient>;
65 static connect(uri: string, options: MongoClientOptions, callback: MongoCallback<MongoClient>): void;
66 /** http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html#connect */
67 connect(): Promise<MongoClient>;
68 connect(callback: MongoCallback<MongoClient>): void;
69 /** http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html#close */
70 close(callback: MongoCallback<void>): void;
71 close(force?: boolean): Promise<void>;
72 close(force: boolean, callback: MongoCallback<void>): void;
73 /** http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html#db */
74 db(dbName?: string, options?: MongoClientCommonOption): Db;
75 /** http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html#isConnected */
76 isConnected(options?: MongoClientCommonOption): boolean;
77 /** http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html#logout */
78 logout(callback: MongoCallback<any>): void;
79 logout(options?: { dbName?: string }): Promise<any>;
80 logout(options: { dbName?: string }, callback: MongoCallback<any>): void;
81 /** http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html#startSession */
82 startSession(options?: SessionOptions): ClientSession;
83 /** http://mongodb.github.io/node-mongodb-native/3.3/api/MongoClient.html#watch */
84 watch<TSchema extends object = { _id: ObjectId }>(
85 pipeline?: object[],
86 options?: ChangeStreamOptions & { session?: ClientSession },
87 ): ChangeStream<TSchema>;
88 /** http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html#withSession */
89 withSession(operation: (session: ClientSession) => Promise<any>): Promise<void>;
90 /** http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html#withSession */
91 withSession(options: SessionOptions, operation: (session: ClientSession) => Promise<any>): Promise<void>;
92
93 readPreference: ReadPreference;
94 writeConcern: WriteConcern;
95}
96
97/**
98 * http://mongodb.github.io/node-mongodb-native/3.1/api/ClientSession.html
99 */
100export interface ClientSession extends EventEmitter {
101 /** The server id associated with this session */
102 id: any;
103 /**
104 * Aborts the currently active transaction in this session.
105 * @param cb Optional callback for completion of this operation
106 */
107 abortTransaction(cb?: MongoCallback<void>): Promise<void>;
108 /**
109 * Advances the operationTime for a ClientSession.
110 */
111 advanceOperationTime(operamtionTime: Timestamp): void;
112 /**
113 * Commits the currently active transaction in this session.
114 * @param cb Optional callback for completion of this operation
115 */
116 commitTransaction(cb?: MongoCallback<void>): Promise<void>;
117
118 /**
119 * Ends this session on the server
120 * @param cb Optional callback for completion of this operation
121 */
122 endSession(cb?: MongoCallback<void>): void;
123 /**
124 * Ends this session on the server
125 * @param options Optional settings. Currently reserved for future use
126 * @param cb Optional callback for completion of this operation
127 */
128 endSession(options: any, cb?: MongoCallback<void>): void;
129
130 /**
131 * Used to determine if this session equals another
132 *
133 * @param session A class representing a client session on the server
134 * @returns Whether the sessions are equal
135 */
136 equals(session: ClientSession): boolean;
137
138 /** Increment the transaction number on the internal ServerSession */
139 incrementTransactionNumber(): void;
140
141 /**
142 * @returns Whether this session is currently in a transaction or not
143 */
144 inTransaction(): boolean;
145
146 /**
147 * Starts a new transaction with the given options.
148 */
149 startTransaction(options?: TransactionOptions): void;
150
151 /**
152 * Runs a provided lambda within a transaction, retrying either the commit operation
153 * or entire transaction as needed (and when the error permits) to better ensure that
154 * the transaction can complete successfully.
155 *
156 * IMPORTANT: This method requires the user to return a Promise, all lambdas that do not
157 * return a Promise will result in undefined behavior.
158 *
159 * @param fn Function to execute with the new session.
160 * @param options Optional settings for the transaction
161 */
162 withTransaction<T>(fn: WithTransactionCallback<T>, options?: TransactionOptions): Promise<void>;
163}
164
165// http://mongodb.github.io/node-mongodb-native/3.1/api/global.html#ReadConcern
166type ReadConcernLevel = 'local' | 'available' | 'majority' | 'linearizable' | 'snapshot';
167
168/**
169 * The MongoDB ReadConcern, which allows for control of the consistency and isolation properties
170 * of the data read from replica sets and replica set shards.
171 * http://mongodb.github.io/node-mongodb-native/3.1/api/global.html#ReadConcern
172 */
173export interface ReadConcern {
174 level: ReadConcernLevel;
175}
176
177/**
178 * A MongoDB WriteConcern, which describes the level of acknowledgement
179 * requested from MongoDB for write operations.
180 * http://mongodb.github.io/node-mongodb-native/3.1/api/global.html#WriteConcern
181 */
182interface WriteConcern {
183 /**
184 * requests acknowledgement that the write operation has
185 * propagated to a specified number of mongod hosts
186 * @default 1
187 */
188 w?: number | 'majority' | string;
189 /**
190 * requests acknowledgement from MongoDB that the write operation has
191 * been written to the journal
192 * @default false
193 */
194 j?: boolean;
195 /**
196 * a time limit, in milliseconds, for the write concern
197 */
198 wtimeout?: number;
199}
200
201/**
202 * Options to pass when creating a Client Session
203 * http://mongodb.github.io/node-mongodb-native/3.1/api/global.html#SessionOptions
204 */
205export interface SessionOptions {
206 /**
207 * Whether causal consistency should be enabled on this session
208 * @default true
209 */
210 causalConsistency?: boolean;
211 /**
212 * The default TransactionOptions to use for transactions started on this session.
213 */
214 defaultTransactionOptions?: TransactionOptions;
215}
216
217/**
218 * Configuration options for a transaction.
219 * http://mongodb.github.io/node-mongodb-native/3.1/api/global.html#TransactionOptions
220 */
221export interface TransactionOptions {
222 readConcern?: ReadConcern;
223 writeConcern?: WriteConcern;
224 readPreference?: ReadPreferenceOrMode;
225}
226
227export interface MongoClientCommonOption {
228 /** Do not make the db an event listener to the original connection. */
229 noListener?: boolean;
230 /** Control if you want to return a cached instance or have a new one created */
231 returnNonCachedInstance?: boolean;
232}
233
234export interface MongoCallback<T> {
235 (error: MongoError, result: T): void;
236}
237
238export type WithTransactionCallback<T> = (session: ClientSession) => Promise<T>;
239
240/**
241 * Creates a new MongoError
242 * see {@link http://mongodb.github.io/node-mongodb-native/3.5/api/MongoError.html}
243 */
244export class MongoError extends Error {
245 constructor(message: string | Error | object);
246 /**
247 * @deprecated
248 */
249 static create(options: string | Error | object): MongoError;
250 /**
251 * Checks the error to see if it has an error label
252 */
253 hasErrorLabel(label: string): boolean;
254 code?: number | string;
255 /**
256 * While not documented, the 'errmsg' prop is AFAIK the only way to find out
257 * which unique index caused a duplicate key error. When you have multiple
258 * unique indexes on a collection, knowing which index caused a duplicate
259 * key error enables you to send better (more precise) error messages to the
260 * client/user (eg. "Email address must be unique" instead of "Both email
261 * address and username must be unique") - which caters for a better (app)
262 * user experience.
263 *
264 * Details: https://github.com/Automattic/mongoose/issues/2129 (issue for
265 * mongoose, but the same applies for the native mongodb driver)
266 *
267 * Note that in mongoose (the link above) the prop in question is called
268 * 'message' while in mongodb it is called 'errmsg'. This can be seen in
269 * multiple places in the source code, for example here:
270 * https://github.com/mongodb/node-mongodb-native/blob/a12aa15ac3eaae3ad5c4166ea1423aec4560f155/test/functional/find_tests.js#L1111
271 */
272 errmsg?: string;
273 name: string;
274}
275
276/**
277 * An error indicating an issue with the network, including TCP errors and timeouts
278 * see {@link https://mongodb.github.io/node-mongodb-native/3.5/api/MongoNetworkError.html}
279 */
280export class MongoNetworkError extends MongoError {
281 constructor(message: string);
282 errorLabels: string[];
283}
284
285/**
286 * An error used when attempting to parse a value (like a connection string)
287 * see {@link https://mongodb.github.io/node-mongodb-native/3.5/api/MongoParseError.html}
288 */
289export class MongoParseError extends MongoError {
290 constructor(message: string);
291}
292
293/** http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html#.connect */
294export interface MongoClientOptions
295 extends DbCreateOptions,
296 ServerOptions,
297 MongosOptions,
298 ReplSetOptions,
299 SocketOptions,
300 SSLOptions,
301 TLSOptions,
302 HighAvailabilityOptions,
303 WriteConcern,
304 UnifiedTopologyOptions {
305 /**
306 * The logging level (error/warn/info/debug)
307 */
308 loggerLevel?: string;
309
310 /**
311 * Custom logger object
312 */
313 logger?: object | log;
314
315 /**
316 * Validate MongoClient passed in options for correctness.
317 * Default: false
318 */
319 validateOptions?: object | boolean;
320
321 /**
322 * The name of the application that created this MongoClient instance.
323 */
324 appname?: string;
325
326 /**
327 * Authentication credentials
328 */
329 auth?: {
330 /**
331 * The username for auth
332 */
333 user: string;
334 /**
335 * The password for auth
336 */
337 password: string;
338 };
339
340 /**
341 * Determines whether or not to use the new url parser. Enables the new, spec-compliant
342 * url parser shipped in the core driver. This url parser fixes a number of problems with
343 * the original parser, and aims to outright replace that parser in the near future.
344 */
345 useNewUrlParser?: boolean;
346
347 /**
348 * number of retries for a tailable cursor
349 * @default 5
350 */
351 numberOfRetries?: number;
352
353 /**
354 * Mechanism for authentication: DEFAULT, GSSAPI, PLAIN, MONGODB-X509, 'MONGODB-CR', SCRAM-SHA-1 or SCRAM-SHA-256
355 */
356 authMechanism?:
357 | 'DEFAULT'
358 | 'GSSAPI'
359 | 'PLAIN'
360 | 'MONGODB-X509'
361 | 'MONGODB-CR'
362 | 'SCRAM-SHA-1'
363 | 'SCRAM-SHA-256'
364 | string;
365
366 /** Type of compression to use */
367 compression?: {
368 /** The selected compressors in preference order */
369 compressors?: Array<'snappy' | 'zlib'>;
370 };
371}
372
373export interface SSLOptions {
374 /**
375 * Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info.
376 */
377 ciphers?: string;
378 /**
379 * Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info.
380 */
381 ecdhCurve?: string;
382 /**
383 * Default:5; Number of connections for each server instance; set to 5 as default for legacy reasons.
384 */
385 poolSize?: number;
386 /**
387 * If present, the connection pool will be initialized with minSize connections, and will never dip below minSize connections
388 */
389 minSize?: number;
390 /**
391 * Use ssl connection (needs to have a mongod server with ssl support)
392 */
393 ssl?: boolean;
394 /**
395 * Default: true; Validate mongod server certificate against ca (mongod server >=2.4 with ssl support required)
396 */
397 sslValidate?: boolean;
398 /**
399 * Default: true; Server identity checking during SSL
400 */
401 checkServerIdentity?: boolean | typeof checkServerIdentity;
402 /**
403 * Array of valid certificates either as Buffers or Strings
404 */
405 sslCA?: ReadonlyArray<Buffer | string>;
406 /**
407 * SSL Certificate revocation list binary buffer
408 */
409 sslCRL?: ReadonlyArray<Buffer | string>;
410 /**
411 * SSL Certificate binary buffer
412 */
413 sslCert?: Buffer | string;
414 /**
415 * SSL Key file binary buffer
416 */
417 sslKey?: Buffer | string;
418 /**
419 * SSL Certificate pass phrase
420 */
421 sslPass?: Buffer | string;
422 /**
423 * String containing the server name requested via TLS SNI.
424 */
425 servername?: string;
426}
427
428export interface TLSOptions {
429 /**
430 * Enable TLS connections
431 * @default false
432 */
433 tls?: boolean;
434 /**
435 * Relax TLS constraints, disabling validation
436 * @default false
437 */
438 tlsInsecure?: boolean;
439 /**
440 * path to file with either a single or bundle of certificate authorities
441 * to be considered trusted when making a TLS connection
442 */
443 tlsCAFile?: string;
444 /**
445 * path to the client certificate file or the client private key file;
446 * in the case that they both are needed, the files should be concatenated
447 */
448 tlsCertificateKeyFile?: string;
449 /**
450 * The password to decrypt the client private key to be used for TLS connections
451 */
452 tlsCertificateKeyFilePassword?: string;
453 /**
454 * Specifies whether or not the driver should error when the server’s TLS certificate is invalid
455 */
456 tlsAllowInvalidCertificates?: boolean;
457 /**
458 * Specifies whether or not the driver should error when there is a mismatch between the server’s hostname
459 * and the hostname specified by the TLS certificate
460 */
461 tlsAllowInvalidHostnames?: boolean;
462}
463
464export interface HighAvailabilityOptions {
465 /**
466 * Default: true; Turn on high availability monitoring.
467 */
468 ha?: boolean;
469 /**
470 * Default: 10000; The High availability period for replicaset inquiry
471 */
472 haInterval?: number;
473 /**
474 * Default: false;
475 */
476 domainsEnabled?: boolean;
477
478 /** The ReadPreference mode as listed here: http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html */
479 readPreference?: ReadPreferenceOrMode;
480 /** An object representing read preference tags, see: http://mongodb.github.io/node-mongodb-native/3.1/api/ReadPreference.html */
481 readPreferenceTags?: string[];
482}
483
484export type ReadPreferenceMode = 'primary' | 'primaryPreferred' | 'secondary' | 'secondaryPreferred' | 'nearest';
485export type ReadPreferenceOrMode = ReadPreference | ReadPreferenceMode;
486export type ReadPreferenceOptions = {
487 hedge?: { enabled?: boolean };
488 /**
489 * Max Secondary Read Staleness in Seconds
490 */
491 maxStalenessSeconds?: number;
492};
493
494// See http://mongodb.github.io/node-mongodb-native/3.1/api/ReadPreference.html
495export class ReadPreference {
496 constructor(mode: ReadPreferenceMode, tags: object, options?: ReadPreferenceOptions);
497 mode: ReadPreferenceMode;
498 tags: any;
499 static PRIMARY: 'primary';
500 static PRIMARY_PREFERRED: 'primaryPreferred';
501 static SECONDARY: 'secondary';
502 static SECONDARY_PREFERRED: 'secondaryPreferred';
503 static NEAREST: 'nearest';
504 isValid(mode: string): boolean;
505 static isValid(mode: string): boolean;
506}
507
508/** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html */
509export interface DbCreateOptions extends CommonOptions {
510 /**
511 * If the database authentication is dependent on another databaseName.
512 */
513 authSource?: string;
514 /**
515 * Default: false; Force server to create _id fields instead of client.
516 */
517 forceServerObjectId?: boolean;
518 /**
519 * Default: false; Use c++ bson parser.
520 */
521 native_parser?: boolean;
522 /**
523 * Serialize functions on any object.
524 */
525 serializeFunctions?: boolean;
526 /**
527 * Specify if the BSON serializer should ignore undefined fields.
528 */
529 ignoreUndefined?: boolean;
530 /**
531 * Return document results as raw BSON buffers.
532 */
533 raw?: boolean;
534 /**
535 * Default: true; Promotes Long values to number if they fit inside the 53 bits resolution.
536 */
537 promoteLongs?: boolean;
538 /**
539 * Default: false; Promotes Binary BSON values to native Node Buffers
540 */
541 promoteBuffers?: boolean;
542 /**
543 * the prefered read preference. use 'ReadPreference' class.
544 */
545 readPreference?: ReadPreferenceOrMode;
546 /**
547 * Default: true; Promotes BSON values to native types where possible, set to false to only receive wrapper types.
548 */
549 promoteValues?: boolean;
550 /**
551 * Custom primary key factory to generate _id values (see Custom primary keys).
552 */
553 pkFactory?: object;
554 /**
555 * ES6 compatible promise constructor
556 */
557 promiseLibrary?: PromiseConstructor;
558 /**
559 * https://docs.mongodb.com/manual/reference/read-concern/#read-concern
560 */
561 readConcern?: ReadConcern | string;
562 /**
563 * Sets a cap on how many operations the driver will buffer up before giving up on getting a
564 * working connection, default is -1 which is unlimited.
565 */
566 bufferMaxEntries?: number;
567}
568
569export interface UnifiedTopologyOptions {
570 /**
571 * Enables the new unified topology layer
572 */
573 useUnifiedTopology?: boolean;
574
575 /**
576 * **Only applies to the unified topology**
577 * The size of the latency window for selecting among multiple suitable servers
578 * @default 15
579 */
580 localThresholdMS?: number;
581
582 /**
583 * With `useUnifiedTopology`, the MongoDB driver will try to find a server to send any given operation to
584 * and keep retrying for `serverSelectionTimeoutMS` milliseconds.
585 * Default: 30000
586 */
587 serverSelectionTimeoutMS?: number;
588
589 /**
590 * **Only applies to the unified topology**
591 * The frequency with which topology updates are scheduled
592 * @default 10000
593 */
594 heartbeatFrequencyMS?: number;
595
596 /**
597 * **Only applies to the unified topology**
598 * The maximum number of connections that may be associated with a pool at a given time.
599 * This includes in use and available connections
600 * @default 10
601 */
602 maxPoolSize?: number;
603
604 /**
605 * **Only applies to the unified topology**
606 * The minimum number of connections that MUST exist at any moment in a single connection pool.
607 * @default 0
608 */
609 minPoolSize?: number;
610
611 /**
612 * **Only applies to the unified topology**
613 * The maximum amount of time a connection should remain idle in the connection pool before being marked idle.
614 * @default Infinity
615 */
616 maxIdleTimeMS?: number;
617
618 /**
619 * **Only applies to the unified topology**
620 * The maximum amount of time operation execution should wait for a connection to become available.
621 * The default is 0 which means there is no limit.
622 * @default 0
623 */
624 waitQueueTimeoutMS?: number;
625}
626
627/** http://mongodb.github.io/node-mongodb-native/3.6/api/Server.html */
628export interface SocketOptions {
629 /**
630 * Reconnect on error.
631 * @default true
632 */
633 autoReconnect?: boolean;
634 /**
635 * TCP Socket NoDelay option.
636 * @default true
637 */
638 noDelay?: boolean;
639 /**
640 * TCP KeepAlive enabled on the socket.
641 * @default true
642 */
643 keepAlive?: boolean;
644 /**
645 * TCP KeepAlive initial delay before sending first keep-alive packet when idle.
646 * @default 30000
647 */
648 keepAliveInitialDelay?: number;
649 /**
650 * TCP Connection timeout setting.
651 * @default 10000
652 */
653 connectTimeoutMS?: number;
654 /**
655 * Version of IP stack. Can be 4, 6 or null.
656 * @default null
657 *
658 * If null, will attempt to connect with IPv6, and will fall back to IPv4 on failure
659 * refer to http://mongodb.github.io/node-mongodb-native/3.6/api/MongoClient.html
660 */
661 family?: 4 | 6 | null;
662 /**
663 * TCP Socket timeout setting.
664 * @default 360000
665 */
666 socketTimeoutMS?: number;
667}
668
669/** http://mongodb.github.io/node-mongodb-native/3.1/api/Server.html */
670export interface ServerOptions extends SSLOptions {
671 /**
672 * If you're connected to a single server or mongos proxy (as opposed to a replica set),
673 * the MongoDB driver will try to reconnect every reconnectInterval milliseconds for reconnectTries
674 * times, and give up afterward. When the driver gives up, the mongoose connection emits a
675 * reconnectFailed event.
676 * @default 30
677 */
678 reconnectTries?: number;
679 /**
680 * Will wait # milliseconds between retries
681 * @default 1000
682 */
683 reconnectInterval?: number;
684 /**
685 * @default true
686 */
687 monitoring?: boolean;
688
689 /**
690 * Enable command monitoring for this client
691 * @default false
692 */
693 monitorCommands?: boolean;
694
695 /**
696 * Socket Options
697 */
698 socketOptions?: SocketOptions;
699
700 /**
701 * The High availability period for replicaset inquiry
702 * @default 10000
703 */
704 haInterval?: number;
705 /**
706 * @default false
707 */
708 domainsEnabled?: boolean;
709
710 /**
711 * Specify a file sync write concern
712 * @default false
713 */
714 fsync?: boolean;
715}
716
717/** http://mongodb.github.io/node-mongodb-native/3.1/api/Mongos.html */
718export interface MongosOptions extends SSLOptions, HighAvailabilityOptions {
719 /**
720 * Default: 15; Cutoff latency point in MS for MongoS proxy selection
721 */
722 acceptableLatencyMS?: number;
723
724 /**
725 * Socket Options
726 */
727 socketOptions?: SocketOptions;
728}
729
730/** http://mongodb.github.io/node-mongodb-native/3.1/api/ReplSet.html */
731export interface ReplSetOptions extends SSLOptions, HighAvailabilityOptions {
732 /**
733 * The max staleness to secondary reads (values under 10 seconds cannot be guaranteed);
734 */
735 maxStalenessSeconds?: number;
736 /**
737 * The name of the replicaset to connect to.
738 */
739 replicaSet?: string;
740 /**
741 * Default: 15 ; Range of servers to pick when using NEAREST (lowest ping ms + the latency fence, ex: range of 1 to (1 + 15) ms)
742 */
743 secondaryAcceptableLatencyMS?: number;
744 connectWithNoPrimary?: boolean;
745 socketOptions?: SocketOptions;
746}
747
748export type ProfilingLevel = 'off' | 'slow_only' | 'all';
749
750// Class documentation : http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html
751export class Db extends EventEmitter {
752 constructor(databaseName: string, serverConfig: Server | ReplSet | Mongos, options?: DbCreateOptions);
753
754 serverConfig: Server | ReplSet | Mongos;
755 bufferMaxEntries: number;
756 databaseName: string;
757 options: any;
758 native_parser: boolean;
759 slaveOk: boolean;
760 writeConcern: WriteConcern;
761
762 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#addUser */
763 addUser(username: string, password: string, callback: MongoCallback<any>): void;
764 addUser(username: string, password: string, options?: DbAddUserOptions): Promise<any>;
765 addUser(username: string, password: string, options: DbAddUserOptions, callback: MongoCallback<any>): void;
766 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#admin */
767 admin(): Admin;
768 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#collection */
769 collection<TSchema = DefaultSchema>(
770 name: string,
771 callback?: MongoCallback<Collection<TSchema>>,
772 ): Collection<TSchema>;
773 collection<TSchema = DefaultSchema>(
774 name: string,
775 options: DbCollectionOptions,
776 callback?: MongoCallback<Collection<TSchema>>,
777 ): Collection<TSchema>;
778 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#collections */
779 collections(): Promise<Array<Collection<Default>>>;
780 collections(callback: MongoCallback<Array<Collection<Default>>>): void;
781 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#command */
782 command(command: object, callback: MongoCallback<any>): void;
783 command(
784 command: object,
785 options?: { readPreference?: ReadPreferenceOrMode; session?: ClientSession },
786 ): Promise<any>;
787 command(
788 command: object,
789 options: { readPreference: ReadPreferenceOrMode; session?: ClientSession },
790 callback: MongoCallback<any>,
791 ): void;
792 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#createCollection */
793 createCollection<TSchema = DefaultSchema>(name: string, callback: MongoCallback<Collection<TSchema>>): void;
794 createCollection<TSchema = DefaultSchema>(
795 name: string,
796 options?: CollectionCreateOptions,
797 ): Promise<Collection<TSchema>>;
798 createCollection<TSchema = DefaultSchema>(
799 name: string,
800 options: CollectionCreateOptions,
801 callback: MongoCallback<Collection<TSchema>>,
802 ): void;
803 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#createIndex */
804 createIndex(name: string, fieldOrSpec: string | object, callback: MongoCallback<any>): void;
805 createIndex(name: string, fieldOrSpec: string | object, options?: IndexOptions): Promise<any>;
806 createIndex(name: string, fieldOrSpec: string | object, options: IndexOptions, callback: MongoCallback<any>): void;
807 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#dropCollection */
808 dropCollection(name: string): Promise<boolean>;
809 dropCollection(name: string, callback: MongoCallback<boolean>): void;
810 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#dropDatabase */
811 dropDatabase(): Promise<any>;
812 dropDatabase(callback: MongoCallback<any>): void;
813 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#executeDbAdminCommand */
814 executeDbAdminCommand(command: object, callback: MongoCallback<any>): void;
815 executeDbAdminCommand(
816 command: object,
817 options?: { readPreference?: ReadPreferenceOrMode; session?: ClientSession },
818 ): Promise<any>;
819 executeDbAdminCommand(
820 command: object,
821 options: { readPreference?: ReadPreferenceOrMode; session?: ClientSession },
822 callback: MongoCallback<any>,
823 ): void;
824 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#indexInformation */
825 indexInformation(name: string, callback: MongoCallback<any>): void;
826 indexInformation(name: string, options?: { full?: boolean; readPreference?: ReadPreferenceOrMode }): Promise<any>;
827 indexInformation(
828 name: string,
829 options: { full?: boolean; readPreference?: ReadPreferenceOrMode },
830 callback: MongoCallback<any>,
831 ): void;
832 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#listCollections */
833 listCollections(
834 filter?: object,
835 options?: {
836 nameOnly?: boolean;
837 batchSize?: number;
838 readPreference?: ReadPreferenceOrMode;
839 session?: ClientSession;
840 },
841 ): CommandCursor;
842 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#profilingInfo */
843 /** @deprecated Query the system.profile collection directly. */
844 profilingInfo(callback: MongoCallback<any>): void;
845 profilingInfo(options?: { session?: ClientSession }): Promise<void>;
846 profilingInfo(options: { session?: ClientSession }, callback: MongoCallback<void>): void;
847 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#profilingLevel */
848 profilingLevel(callback: MongoCallback<ProfilingLevel>): void;
849 profilingLevel(options?: { session?: ClientSession }): Promise<ProfilingLevel>;
850 profilingLevel(options: { session?: ClientSession }, callback: MongoCallback<ProfilingLevel>): void;
851 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#removeUser */
852 removeUser(username: string, callback: MongoCallback<any>): void;
853 removeUser(username: string, options?: CommonOptions): Promise<any>;
854 removeUser(username: string, options: CommonOptions, callback: MongoCallback<any>): void;
855 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#renameCollection */
856 renameCollection<TSchema = DefaultSchema>(
857 fromCollection: string,
858 toCollection: string,
859 callback: MongoCallback<Collection<TSchema>>,
860 ): void;
861 renameCollection<TSchema = DefaultSchema>(
862 fromCollection: string,
863 toCollection: string,
864 options?: { dropTarget?: boolean },
865 ): Promise<Collection<TSchema>>;
866 renameCollection<TSchema = DefaultSchema>(
867 fromCollection: string,
868 toCollection: string,
869 options: { dropTarget?: boolean },
870 callback: MongoCallback<Collection<TSchema>>,
871 ): void;
872 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#setProfilingLevel */
873 setProfilingLevel(level: ProfilingLevel, callback: MongoCallback<ProfilingLevel>): void;
874 setProfilingLevel(level: ProfilingLevel, options?: { session?: ClientSession }): Promise<ProfilingLevel>;
875 setProfilingLevel(
876 level: ProfilingLevel,
877 options: { session?: ClientSession },
878 callback: MongoCallback<ProfilingLevel>,
879 ): void;
880 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#stats */
881 stats(callback: MongoCallback<any>): void;
882 stats(options?: { scale?: number }): Promise<any>;
883 stats(options: { scale?: number }, callback: MongoCallback<any>): void;
884 /** http://mongodb.github.io/node-mongodb-native/3.3/api/Db.html#watch */
885 watch<TSchema extends object = { _id: ObjectId }>(
886 pipeline?: object[],
887 options?: ChangeStreamOptions & { session?: ClientSession },
888 ): ChangeStream<TSchema>;
889}
890
891export interface CommonOptions extends WriteConcern {
892 session?: ClientSession;
893}
894
895/**
896 * @deprecated
897 * @see http://mongodb.github.io/node-mongodb-native/3.1/api/Server.html
898 */
899export class Server extends EventEmitter {
900 constructor(host: string, port: number, options?: ServerOptions);
901
902 connections(): any[];
903}
904
905/**
906 * @deprecated
907 * @see http://mongodb.github.io/node-mongodb-native/3.1/api/ReplSet.html
908 */
909export class ReplSet extends EventEmitter {
910 constructor(servers: Server[], options?: ReplSetOptions);
911
912 connections(): any[];
913}
914
915/**
916 * @deprecated
917 * @see http://mongodb.github.io/node-mongodb-native/3.1/api/Mongos.html
918 */
919export class Mongos extends EventEmitter {
920 constructor(servers: Server[], options?: MongosOptions);
921
922 connections(): any[];
923}
924
925/**
926 * @deprecated
927 * @see http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#addUser
928 */
929export interface DbAddUserOptions extends CommonOptions {
930 customData?: object;
931 roles?: object[];
932}
933
934/** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#createCollection */
935export interface CollectionCreateOptions extends CommonOptions {
936 raw?: boolean;
937 pkFactory?: object;
938 readPreference?: ReadPreferenceOrMode;
939 serializeFunctions?: boolean;
940 /**
941 * @deprecated
942 * @see https://jira.mongodb.org/browse/NODE-2746
943 */
944 strict?: boolean;
945 capped?: boolean;
946 /**
947 * @deprecated
948 */
949 autoIndexId?: boolean;
950 size?: number;
951 max?: number;
952 flags?: number;
953 storageEngine?: object;
954 validator?: object;
955 validationLevel?: 'off' | 'strict' | 'moderate';
956 validationAction?: 'error' | 'warn';
957 indexOptionDefaults?: object;
958 viewOn?: string;
959 pipeline?: any[];
960 collation?: CollationDocument;
961}
962
963/** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#collection */
964export interface DbCollectionOptions extends CommonOptions {
965 raw?: boolean;
966 pkFactory?: object;
967 readPreference?: ReadPreferenceOrMode;
968 serializeFunctions?: boolean;
969 strict?: boolean;
970 readConcern?: ReadConcern;
971}
972
973/** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#createIndex */
974export interface IndexOptions extends CommonOptions {
975 /**
976 * Creates an unique index.
977 */
978 unique?: boolean;
979 /**
980 * Creates a sparse index.
981 */
982 sparse?: boolean;
983 /**
984 * Creates the index in the background, yielding whenever possible.
985 */
986 background?: boolean;
987 /**
988 * A unique index cannot be created on a key that has pre-existing duplicate values.
989 *
990 * If you would like to create the index anyway, keeping the first document the database indexes and
991 * deleting all subsequent documents that have duplicate value
992 */
993 dropDups?: boolean;
994 /**
995 * For geo spatial indexes set the lower bound for the co-ordinates.
996 */
997 min?: number;
998 /**
999 * For geo spatial indexes set the high bound for the co-ordinates.
1000 */
1001 max?: number;
1002 /**
1003 * Specify the format version of the indexes.
1004 */
1005 v?: number;
1006 /**
1007 * Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher)
1008 */
1009 expireAfterSeconds?: number;
1010 /**
1011 * Override the auto generated index name (useful if the resulting name is larger than 128 bytes)
1012 */
1013 name?: string;
1014 /**
1015 * Creates a partial index based on the given filter object (MongoDB 3.2 or higher)
1016 */
1017 partialFilterExpression?: any;
1018 collation?: CollationDocument;
1019 default_language?: string;
1020}
1021
1022/** http://mongodb.github.io/node-mongodb-native/3.1/api/Admin.html */
1023export interface Admin {
1024 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Admin.html#addUser */
1025 addUser(username: string, password: string, callback: MongoCallback<any>): void;
1026 addUser(username: string, password: string, options?: AddUserOptions): Promise<any>;
1027 addUser(username: string, password: string, options: AddUserOptions, callback: MongoCallback<any>): void;
1028 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Admin.html#buildInfo */
1029 buildInfo(options?: { session?: ClientSession }): Promise<any>;
1030 buildInfo(options: { session?: ClientSession }, callback: MongoCallback<any>): void;
1031 buildInfo(callback: MongoCallback<any>): void;
1032 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Admin.html#command */
1033 command(command: object, callback: MongoCallback<any>): void;
1034 command(command: object, options?: { readPreference?: ReadPreferenceOrMode; maxTimeMS?: number }): Promise<any>;
1035 command(
1036 command: object,
1037 options: { readPreference?: ReadPreferenceOrMode; maxTimeMS?: number },
1038 callback: MongoCallback<any>,
1039 ): void;
1040 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Admin.html#listDatabases */
1041 listDatabases(options?: { nameOnly?: boolean; session?: ClientSession }): Promise<any>;
1042 listDatabases(options: { nameOnly?: boolean; session?: ClientSession }, callback: MongoCallback<any>): void;
1043 listDatabases(callback: MongoCallback<any>): void;
1044 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Admin.html#ping */
1045 ping(options?: { session?: ClientSession }): Promise<any>;
1046 ping(options: { session?: ClientSession }, callback: MongoCallback<any>): void;
1047 ping(callback: MongoCallback<any>): void;
1048 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Admin.html#removeUser */
1049 removeUser(username: string, callback: MongoCallback<any>): void;
1050 removeUser(username: string, options?: FSyncOptions): Promise<any>;
1051 removeUser(username: string, options: FSyncOptions, callback: MongoCallback<any>): void;
1052 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Admin.html#replSetGetStatus */
1053 replSetGetStatus(options?: { session?: ClientSession }): Promise<any>;
1054 replSetGetStatus(options: { session?: ClientSession }, callback: MongoCallback<any>): void;
1055 replSetGetStatus(callback: MongoCallback<any>): void;
1056 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Admin.html#serverInfo */
1057 serverInfo(): Promise<any>;
1058 serverInfo(callback: MongoCallback<any>): void;
1059 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Admin.html#serverStatus */
1060 serverStatus(options?: { session?: ClientSession }): Promise<any>;
1061 serverStatus(options: { session?: ClientSession }, callback: MongoCallback<any>): void;
1062 serverStatus(callback: MongoCallback<any>): void;
1063 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Admin.html#validateCollection */
1064 validateCollection(collectionNme: string, callback: MongoCallback<any>): void;
1065 validateCollection(collectionNme: string, options?: object): Promise<any>;
1066 validateCollection(collectionNme: string, options: object, callback: MongoCallback<any>): void;
1067}
1068
1069/** http://mongodb.github.io/node-mongodb-native/3.1/api/Admin.html#addUser */
1070export interface AddUserOptions extends CommonOptions {
1071 fsync: boolean;
1072 customData?: object;
1073 roles?: object[];
1074}
1075
1076/** http://mongodb.github.io/node-mongodb-native/3.1/api/Admin.html#removeUser */
1077export interface FSyncOptions extends CommonOptions {
1078 fsync?: boolean;
1079}
1080
1081// TypeScript Omit (Exclude to be specific) does not work for objects with an "any" indexed type, and breaks discriminated unions
1082type EnhancedOmit<T, K> = string | number extends keyof T
1083 ? T // T has indexed type e.g. { _id: string; [k: string]: any; } or it is "any"
1084 : T extends any
1085 ? Pick<T, Exclude<keyof T, K>> // discriminated unions
1086 : never;
1087
1088type ExtractIdType<TSchema> = TSchema extends { _id: infer U } // user has defined a type for _id
1089 ? {} extends U
1090 ? Exclude<U, {}>
1091 : unknown extends U
1092 ? ObjectId
1093 : U
1094 : ObjectId; // user has not defined _id on schema
1095
1096// this makes _id optional
1097export type OptionalId<TSchema extends { _id?: any }> = ObjectId extends TSchema['_id']
1098 ? // a Schema with ObjectId _id type or "any" or "indexed type" provided
1099 EnhancedOmit<TSchema, '_id'> & { _id?: ExtractIdType<TSchema> }
1100 : // a Schema provided but _id type is not ObjectId
1101 WithId<TSchema>;
1102
1103// this adds _id as a required property
1104export type WithId<TSchema> = EnhancedOmit<TSchema, '_id'> & { _id: ExtractIdType<TSchema> };
1105
1106/** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html */
1107export interface Collection<TSchema extends { [key: string]: any } = DefaultSchema> {
1108 /**
1109 * Get the collection name.
1110 */
1111 collectionName: string;
1112 /**
1113 * Get the full collection namespace.
1114 */
1115 namespace: string;
1116 /**
1117 * The current write concern values.
1118 */
1119 writeConcern: WriteConcern;
1120 /**
1121 * The current read concern values.
1122 */
1123 readConcern: ReadConcern;
1124 /**
1125 * Get current index hint for collection.
1126 */
1127 hint: any;
1128 /** http://mongodb.github.io/node-mongodb-native/3.0/api/Collection.html#aggregate */
1129 aggregate<T = TSchema>(callback: MongoCallback<AggregationCursor<T>>): AggregationCursor<T>;
1130 aggregate<T = TSchema>(pipeline: object[], callback: MongoCallback<AggregationCursor<T>>): AggregationCursor<T>;
1131 aggregate<T = TSchema>(
1132 pipeline?: object[],
1133 options?: CollectionAggregationOptions,
1134 callback?: MongoCallback<AggregationCursor<T>>,
1135 ): AggregationCursor<T>;
1136 /** http://mongodb.github.io/node-mongodb-native/3.0/api/Collection.html#bulkWrite */
1137 bulkWrite(operations: Array<BulkWriteOperation<TSchema>>, callback: MongoCallback<BulkWriteOpResultObject>): void;
1138 bulkWrite(
1139 operations: Array<BulkWriteOperation<TSchema>>,
1140 options?: CollectionBulkWriteOptions,
1141 ): Promise<BulkWriteOpResultObject>;
1142 bulkWrite(
1143 operations: Array<BulkWriteOperation<TSchema>>,
1144 options: CollectionBulkWriteOptions,
1145 callback: MongoCallback<BulkWriteOpResultObject>,
1146 ): void;
1147 /**
1148 * http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#count
1149 * @deprecated Use countDocuments or estimatedDocumentCount
1150 */
1151 count(callback: MongoCallback<number>): void;
1152 count(query: FilterQuery<TSchema>, callback: MongoCallback<number>): void;
1153 count(query?: FilterQuery<TSchema>, options?: MongoCountPreferences): Promise<number>;
1154 count(query: FilterQuery<TSchema>, options: MongoCountPreferences, callback: MongoCallback<number>): void;
1155 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#countDocuments */
1156 countDocuments(callback: MongoCallback<number>): void;
1157 countDocuments(query: FilterQuery<TSchema>, callback: MongoCallback<number>): void;
1158 countDocuments(query?: FilterQuery<TSchema>, options?: MongoCountPreferences): Promise<number>;
1159 countDocuments(query: FilterQuery<TSchema>, options: MongoCountPreferences, callback: MongoCallback<number>): void;
1160 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#createIndex */
1161 createIndex(fieldOrSpec: string | any, callback: MongoCallback<string>): void;
1162 createIndex(fieldOrSpec: string | any, options?: IndexOptions): Promise<string>;
1163 createIndex(fieldOrSpec: string | any, options: IndexOptions, callback: MongoCallback<string>): void;
1164 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#createIndexes and http://docs.mongodb.org/manual/reference/command/createIndexes/ */
1165 createIndexes(indexSpecs: IndexSpecification[], callback: MongoCallback<any>): void;
1166 createIndexes(indexSpecs: IndexSpecification[], options?: { session?: ClientSession }): Promise<any>;
1167 createIndexes(
1168 indexSpecs: IndexSpecification[],
1169 options: { session?: ClientSession },
1170 callback: MongoCallback<any>,
1171 ): void;
1172 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#deleteMany */
1173 deleteMany(filter: FilterQuery<TSchema>, callback: MongoCallback<DeleteWriteOpResultObject>): void;
1174 deleteMany(filter: FilterQuery<TSchema>, options?: CommonOptions): Promise<DeleteWriteOpResultObject>;
1175 deleteMany(
1176 filter: FilterQuery<TSchema>,
1177 options: CommonOptions,
1178 callback: MongoCallback<DeleteWriteOpResultObject>,
1179 ): void;
1180 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#deleteOne */
1181 deleteOne(filter: FilterQuery<TSchema>, callback: MongoCallback<DeleteWriteOpResultObject>): void;
1182 deleteOne(
1183 filter: FilterQuery<TSchema>,
1184 options?: CommonOptions & { bypassDocumentValidation?: boolean },
1185 ): Promise<DeleteWriteOpResultObject>;
1186 deleteOne(
1187 filter: FilterQuery<TSchema>,
1188 options: CommonOptions & { bypassDocumentValidation?: boolean },
1189 callback: MongoCallback<DeleteWriteOpResultObject>,
1190 ): void;
1191 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#distinct */
1192 distinct<Key extends keyof WithId<TSchema>>(
1193 key: Key,
1194 callback: MongoCallback<Array<FlattenIfArray<WithId<TSchema>[Key]>>>,
1195 ): void;
1196 distinct<Key extends keyof WithId<TSchema>>(
1197 key: Key,
1198 query: FilterQuery<TSchema>,
1199 callback: MongoCallback<Array<FlattenIfArray<WithId<TSchema>[Key]>>>,
1200 ): void;
1201 distinct<Key extends keyof WithId<TSchema>>(
1202 key: Key,
1203 query?: FilterQuery<TSchema>,
1204 options?: MongoDistinctPreferences,
1205 ): Promise<Array<FlattenIfArray<WithId<TSchema>[Key]>>>;
1206 distinct<Key extends keyof WithId<TSchema>>(
1207 key: Key,
1208 query: FilterQuery<TSchema>,
1209 options: MongoDistinctPreferences,
1210 callback: MongoCallback<Array<FlattenIfArray<WithId<TSchema>[Key]>>>,
1211 ): void;
1212 distinct(key: string, callback: MongoCallback<any[]>): void;
1213 distinct(key: string, query: FilterQuery<TSchema>, callback: MongoCallback<any[]>): void;
1214 distinct(key: string, query?: FilterQuery<TSchema>, options?: MongoDistinctPreferences): Promise<any[]>;
1215 distinct(
1216 key: string,
1217 query: FilterQuery<TSchema>,
1218 options: MongoDistinctPreferences,
1219 callback: MongoCallback<any[]>,
1220 ): void;
1221 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#drop */
1222 drop(options?: { session: ClientSession }): Promise<any>;
1223 drop(callback: MongoCallback<any>): void;
1224 drop(options: { session: ClientSession }, callback: MongoCallback<any>): void;
1225 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#dropIndex */
1226 dropIndex(indexName: string, callback: MongoCallback<any>): void;
1227 dropIndex(indexName: string, options?: CommonOptions & { maxTimeMS?: number }): Promise<any>;
1228 dropIndex(indexName: string, options: CommonOptions & { maxTimeMS?: number }, callback: MongoCallback<any>): void;
1229 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#dropIndexes */
1230 dropIndexes(options?: { session?: ClientSession; maxTimeMS?: number }): Promise<any>;
1231 dropIndexes(callback?: MongoCallback<any>): void;
1232 dropIndexes(options: { session?: ClientSession; maxTimeMS?: number }, callback: MongoCallback<any>): void;
1233 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#estimatedDocumentCount */
1234 estimatedDocumentCount(callback: MongoCallback<number>): void;
1235 estimatedDocumentCount(query: FilterQuery<TSchema>, callback: MongoCallback<number>): void;
1236 estimatedDocumentCount(query?: FilterQuery<TSchema>, options?: MongoCountPreferences): Promise<number>;
1237 estimatedDocumentCount(
1238 query: FilterQuery<TSchema>,
1239 options: MongoCountPreferences,
1240 callback: MongoCallback<number>,
1241 ): void;
1242 /** http://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html#find */
1243 find<T = TSchema>(query?: FilterQuery<TSchema>): Cursor<T>;
1244 find<T = TSchema>(
1245 query: FilterQuery<TSchema>,
1246 options?: FindOneOptions<T extends TSchema ? TSchema : T>,
1247 ): Cursor<T>;
1248 /** http://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html#findOne */
1249 findOne<T = TSchema>(
1250 filter: FilterQuery<TSchema>,
1251 callback: MongoCallback<T extends TSchema ? TSchema : T | null>,
1252 ): void;
1253 findOne<T = TSchema>(
1254 filter: FilterQuery<TSchema>,
1255 options?: FindOneOptions<T extends TSchema ? TSchema : T>,
1256 ): Promise<T | null>;
1257 findOne<T = TSchema>(
1258 filter: FilterQuery<TSchema>,
1259 options: FindOneOptions<T extends TSchema ? TSchema : T>,
1260 callback: MongoCallback<T extends TSchema ? TSchema : T | null>,
1261 ): void;
1262 /** http://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html#findOneAndDelete */
1263 findOneAndDelete(
1264 filter: FilterQuery<TSchema>,
1265 callback: MongoCallback<FindAndModifyWriteOpResultObject<TSchema>>,
1266 ): void;
1267 findOneAndDelete(
1268 filter: FilterQuery<TSchema>,
1269 options?: FindOneAndDeleteOption<TSchema>,
1270 ): Promise<FindAndModifyWriteOpResultObject<TSchema>>;
1271 findOneAndDelete(
1272 filter: FilterQuery<TSchema>,
1273 options: FindOneAndDeleteOption<TSchema>,
1274 callback: MongoCallback<FindAndModifyWriteOpResultObject<TSchema>>,
1275 ): void;
1276 /** http://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html#findOneAndReplace */
1277 findOneAndReplace(
1278 filter: FilterQuery<TSchema>,
1279 replacement: object,
1280 callback: MongoCallback<FindAndModifyWriteOpResultObject<TSchema>>,
1281 ): void;
1282 findOneAndReplace(
1283 filter: FilterQuery<TSchema>,
1284 replacement: object,
1285 options?: FindOneAndReplaceOption<TSchema>,
1286 ): Promise<FindAndModifyWriteOpResultObject<TSchema>>;
1287 findOneAndReplace(
1288 filter: FilterQuery<TSchema>,
1289 replacement: object,
1290 options: FindOneAndReplaceOption<TSchema>,
1291 callback: MongoCallback<FindAndModifyWriteOpResultObject<TSchema>>,
1292 ): void;
1293 /** http://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html#findOneAndUpdate */
1294 findOneAndUpdate(
1295 filter: FilterQuery<TSchema>,
1296 update: UpdateQuery<TSchema> | TSchema,
1297 callback: MongoCallback<FindAndModifyWriteOpResultObject<TSchema>>,
1298 ): void;
1299 findOneAndUpdate(
1300 filter: FilterQuery<TSchema>,
1301 update: UpdateQuery<TSchema> | TSchema,
1302 options?: FindOneAndUpdateOption<TSchema>,
1303 ): Promise<FindAndModifyWriteOpResultObject<TSchema>>;
1304 findOneAndUpdate(
1305 filter: FilterQuery<TSchema>,
1306 update: UpdateQuery<TSchema> | TSchema,
1307 options: FindOneAndUpdateOption<TSchema>,
1308 callback: MongoCallback<FindAndModifyWriteOpResultObject<TSchema>>,
1309 ): void;
1310 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#geoHaystackSearch */
1311 geoHaystackSearch(x: number, y: number, callback: MongoCallback<any>): void;
1312 geoHaystackSearch(x: number, y: number, options?: GeoHaystackSearchOptions): Promise<any>;
1313 geoHaystackSearch(x: number, y: number, options: GeoHaystackSearchOptions, callback: MongoCallback<any>): void;
1314 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#group */
1315 /** @deprecated MongoDB 3.6 or higher no longer supports the group command. We recommend rewriting using the aggregation framework. */
1316 group(
1317 keys: object | any[] | Function | Code,
1318 condition: object,
1319 initial: object,
1320 reduce: Function | Code,
1321 finalize: Function | Code,
1322 command: boolean,
1323 callback: MongoCallback<any>,
1324 ): void;
1325 /** @deprecated MongoDB 3.6 or higher no longer supports the group command. We recommend rewriting using the aggregation framework. */
1326 group(
1327 keys: object | any[] | Function | Code,
1328 condition: object,
1329 initial: object,
1330 reduce: Function | Code,
1331 finalize: Function | Code,
1332 command: boolean,
1333 options?: { readPreference?: ReadPreferenceOrMode; session?: ClientSession },
1334 ): Promise<any>;
1335 /** @deprecated MongoDB 3.6 or higher no longer supports the group command. We recommend rewriting using the aggregation framework. */
1336 group(
1337 keys: object | any[] | Function | Code,
1338 condition: object,
1339 initial: object,
1340 reduce: Function | Code,
1341 finalize: Function | Code,
1342 command: boolean,
1343 options: {
1344 readPreference?: ReadPreferenceOrMode;
1345 session?: ClientSession;
1346 },
1347 callback: MongoCallback<any>,
1348 ): void;
1349 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#indexes */
1350 indexes(options?: { session: ClientSession }): Promise<any>;
1351 indexes(callback: MongoCallback<any>): void;
1352 indexes(options: { session?: ClientSession }, callback: MongoCallback<any>): void;
1353 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#indexExists */
1354 indexExists(indexes: string | string[], callback: MongoCallback<boolean>): void;
1355 indexExists(indexes: string | string[], options?: { session: ClientSession }): Promise<boolean>;
1356 indexExists(
1357 indexes: string | string[],
1358 options: { session: ClientSession },
1359 callback: MongoCallback<boolean>,
1360 ): void;
1361 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#indexInformation */
1362 indexInformation(callback: MongoCallback<any>): void;
1363 indexInformation(options?: { full: boolean; session: ClientSession }): Promise<any>;
1364 indexInformation(options: { full: boolean; session: ClientSession }, callback: MongoCallback<any>): void;
1365 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#initializeOrderedBulkOp */
1366 initializeOrderedBulkOp(options?: CommonOptions): OrderedBulkOperation;
1367 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#initializeUnorderedBulkOp */
1368 initializeUnorderedBulkOp(options?: CommonOptions): UnorderedBulkOperation;
1369 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#insertOne */
1370 /** @deprecated Use insertOne, insertMany or bulkWrite */
1371 insert(docs: OptionalId<TSchema>, callback: MongoCallback<InsertWriteOpResult<WithId<TSchema>>>): void;
1372 /** @deprecated Use insertOne, insertMany or bulkWrite */
1373 insert(
1374 docs: OptionalId<TSchema>,
1375 options?: CollectionInsertOneOptions,
1376 ): Promise<InsertWriteOpResult<WithId<TSchema>>>;
1377 /** @deprecated Use insertOne, insertMany or bulkWrite */
1378 insert(
1379 docs: OptionalId<TSchema>,
1380 options: CollectionInsertOneOptions,
1381 callback: MongoCallback<InsertWriteOpResult<WithId<TSchema>>>,
1382 ): void;
1383 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#insertMany */
1384 insertMany(docs: Array<OptionalId<TSchema>>, callback: MongoCallback<InsertWriteOpResult<WithId<TSchema>>>): void;
1385 insertMany(
1386 docs: Array<OptionalId<TSchema>>,
1387 options?: CollectionInsertManyOptions,
1388 ): Promise<InsertWriteOpResult<WithId<TSchema>>>;
1389 insertMany(
1390 docs: Array<OptionalId<TSchema>>,
1391 options: CollectionInsertManyOptions,
1392 callback: MongoCallback<InsertWriteOpResult<WithId<TSchema>>>,
1393 ): void;
1394 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#insertOne */
1395 insertOne(docs: OptionalId<TSchema>, callback: MongoCallback<InsertOneWriteOpResult<WithId<TSchema>>>): void;
1396 insertOne(
1397 docs: OptionalId<TSchema>,
1398 options?: CollectionInsertOneOptions,
1399 ): Promise<InsertOneWriteOpResult<WithId<TSchema>>>;
1400 insertOne(
1401 docs: OptionalId<TSchema>,
1402 options: CollectionInsertOneOptions,
1403 callback: MongoCallback<InsertOneWriteOpResult<WithId<TSchema>>>,
1404 ): void;
1405 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#isCapped */
1406 isCapped(options?: { session: ClientSession }): Promise<any>;
1407 isCapped(callback: MongoCallback<any>): void;
1408 isCapped(options: { session: ClientSession }, callback: MongoCallback<any>): void;
1409 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#listIndexes */
1410 listIndexes(options?: {
1411 batchSize?: number;
1412 readPreference?: ReadPreferenceOrMode;
1413 session?: ClientSession;
1414 }): CommandCursor;
1415 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#mapReduce */
1416 mapReduce<TKey, TValue>(
1417 map: CollectionMapFunction<TSchema> | string,
1418 reduce: CollectionReduceFunction<TKey, TValue> | string,
1419 callback: MongoCallback<any>,
1420 ): void;
1421 mapReduce<TKey, TValue>(
1422 map: CollectionMapFunction<TSchema> | string,
1423 reduce: CollectionReduceFunction<TKey, TValue> | string,
1424 options?: MapReduceOptions,
1425 ): Promise<any>;
1426 mapReduce<TKey, TValue>(
1427 map: CollectionMapFunction<TSchema> | string,
1428 reduce: CollectionReduceFunction<TKey, TValue> | string,
1429 options: MapReduceOptions,
1430 callback: MongoCallback<any>,
1431 ): void;
1432 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#options */
1433 options(options?: { session: ClientSession }): Promise<any>;
1434 options(callback: MongoCallback<any>): void;
1435 options(options: { session: ClientSession }, callback: MongoCallback<any>): void;
1436 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#parallelCollectionScan */
1437 parallelCollectionScan(callback: MongoCallback<Array<Cursor<any>>>): void;
1438 parallelCollectionScan(options?: ParallelCollectionScanOptions): Promise<Array<Cursor<any>>>;
1439 parallelCollectionScan(options: ParallelCollectionScanOptions, callback: MongoCallback<Array<Cursor<any>>>): void;
1440 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#reIndex */
1441 reIndex(options?: { session: ClientSession }): Promise<any>;
1442 reIndex(callback: MongoCallback<any>): void;
1443 reIndex(options: { session: ClientSession }, callback: MongoCallback<any>): void;
1444 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#remove */
1445 /** @deprecated Use use deleteOne, deleteMany or bulkWrite */
1446 remove(selector: object, callback: MongoCallback<WriteOpResult>): void;
1447 /** @deprecated Use use deleteOne, deleteMany or bulkWrite */
1448 remove(selector: object, options?: CommonOptions & { single?: boolean }): Promise<WriteOpResult>;
1449 /** @deprecated Use use deleteOne, deleteMany or bulkWrite */
1450 remove(
1451 selector: object,
1452 options?: CommonOptions & { single?: boolean },
1453 callback?: MongoCallback<WriteOpResult>,
1454 ): void;
1455 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#rename */
1456 rename(newName: string, callback: MongoCallback<Collection<TSchema>>): void;
1457 rename(newName: string, options?: { dropTarget?: boolean; session?: ClientSession }): Promise<Collection<TSchema>>;
1458 rename(
1459 newName: string,
1460 options: { dropTarget?: boolean; session?: ClientSession },
1461 callback: MongoCallback<Collection<TSchema>>,
1462 ): void;
1463 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#replaceOne */
1464 replaceOne(filter: FilterQuery<TSchema>, doc: TSchema, callback: MongoCallback<ReplaceWriteOpResult>): void;
1465 replaceOne(filter: FilterQuery<TSchema>, doc: TSchema, options?: ReplaceOneOptions): Promise<ReplaceWriteOpResult>;
1466 replaceOne(
1467 filter: FilterQuery<TSchema>,
1468 doc: TSchema,
1469 options: ReplaceOneOptions,
1470 callback: MongoCallback<ReplaceWriteOpResult>,
1471 ): void;
1472 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#save */
1473 /** @deprecated Use insertOne, insertMany, updateOne or updateMany */
1474 save(doc: TSchema, callback: MongoCallback<WriteOpResult>): void;
1475 /** @deprecated Use insertOne, insertMany, updateOne or updateMany */
1476 save(doc: TSchema, options?: CommonOptions): Promise<WriteOpResult>;
1477 /** @deprecated Use insertOne, insertMany, updateOne or updateMany */
1478 save(doc: TSchema, options: CommonOptions, callback: MongoCallback<WriteOpResult>): void;
1479 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#stats */
1480 stats(callback: MongoCallback<CollStats>): void;
1481 stats(options?: { scale: number; session?: ClientSession }): Promise<CollStats>;
1482 stats(options: { scale: number; session?: ClientSession }, callback: MongoCallback<CollStats>): void;
1483 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#update */
1484 /** @deprecated use updateOne, updateMany or bulkWrite */
1485 update(
1486 filter: FilterQuery<TSchema>,
1487 update: UpdateQuery<TSchema> | Partial<TSchema>,
1488 callback: MongoCallback<WriteOpResult>,
1489 ): void;
1490 /** @deprecated use updateOne, updateMany or bulkWrite */
1491 update(
1492 filter: FilterQuery<TSchema>,
1493 update: UpdateQuery<TSchema> | Partial<TSchema>,
1494 options?: UpdateOneOptions & { multi?: boolean },
1495 ): Promise<WriteOpResult>;
1496 /** @deprecated use updateOne, updateMany or bulkWrite */
1497 update(
1498 filter: FilterQuery<TSchema>,
1499 update: UpdateQuery<TSchema> | Partial<TSchema>,
1500 options: UpdateOneOptions & { multi?: boolean },
1501 callback: MongoCallback<WriteOpResult>,
1502 ): void;
1503 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#updateMany */
1504 updateMany(
1505 filter: FilterQuery<TSchema>,
1506 update: UpdateQuery<TSchema> | Partial<TSchema>,
1507 callback: MongoCallback<UpdateWriteOpResult>,
1508 ): void;
1509 updateMany(
1510 filter: FilterQuery<TSchema>,
1511 update: UpdateQuery<TSchema> | Partial<TSchema>,
1512 options?: UpdateManyOptions,
1513 ): Promise<UpdateWriteOpResult>;
1514 updateMany(
1515 filter: FilterQuery<TSchema>,
1516 update: UpdateQuery<TSchema> | Partial<TSchema>,
1517 options: UpdateManyOptions,
1518 callback: MongoCallback<UpdateWriteOpResult>,
1519 ): void;
1520 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#updateOne */
1521 updateOne(
1522 filter: FilterQuery<TSchema>,
1523 update: UpdateQuery<TSchema> | Partial<TSchema>,
1524 callback: MongoCallback<UpdateWriteOpResult>,
1525 ): void;
1526 updateOne(
1527 filter: FilterQuery<TSchema>,
1528 update: UpdateQuery<TSchema> | Partial<TSchema>,
1529 options?: UpdateOneOptions,
1530 ): Promise<UpdateWriteOpResult>;
1531 updateOne(
1532 filter: FilterQuery<TSchema>,
1533 update: UpdateQuery<TSchema> | Partial<TSchema>,
1534 options: UpdateOneOptions,
1535 callback: MongoCallback<UpdateWriteOpResult>,
1536 ): void;
1537 /**
1538 * @param pipeline - an array of
1539 * {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/ aggregation pipeline stages}
1540 * through which to pass change stream documents. This allows for filtering (using `$match`) and manipulating
1541 * the change stream documents.
1542 *
1543 * @param options - optional settings
1544 * @see http://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html#watch
1545 */
1546 watch<T = TSchema>(
1547 pipeline?: object[],
1548 options?: ChangeStreamOptions & { session?: ClientSession },
1549 ): ChangeStream<T>;
1550 /**
1551 * @param options - optional settings
1552 * @see http://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html#watch
1553 */
1554 watch<T = TSchema>(options?: ChangeStreamOptions & { session?: ClientSession }): ChangeStream<T>;
1555}
1556
1557/** Update Query */
1558type KeysOfAType<TSchema, Type> = {
1559 [key in keyof TSchema]: NonNullable<TSchema[key]> extends Type ? key : never;
1560}[keyof TSchema];
1561type KeysOfOtherType<TSchema, Type> = {
1562 [key in keyof TSchema]: NonNullable<TSchema[key]> extends Type ? never : key;
1563}[keyof TSchema];
1564
1565type AcceptedFields<TSchema, FieldType, AssignableType> = {
1566 readonly [key in KeysOfAType<TSchema, FieldType>]?: AssignableType;
1567};
1568
1569/** It avoid uses fields of non Type */
1570type NotAcceptedFields<TSchema, FieldType> = {
1571 readonly [key in KeysOfOtherType<TSchema, FieldType>]?: never;
1572};
1573
1574type DotAndArrayNotation<AssignableType> = {
1575 readonly [key: string]: AssignableType;
1576};
1577
1578type ReadonlyPartial<TSchema> = {
1579 readonly [key in keyof TSchema]?: TSchema[key];
1580};
1581
1582export type OnlyFieldsOfType<TSchema, FieldType = any, AssignableType = FieldType> = AcceptedFields<
1583 TSchema,
1584 FieldType,
1585 AssignableType
1586> &
1587 NotAcceptedFields<TSchema, FieldType> &
1588 DotAndArrayNotation<AssignableType>;
1589
1590export type MatchKeysAndValues<TSchema> = ReadonlyPartial<TSchema> & DotAndArrayNotation<any>;
1591
1592type Unpacked<Type> = Type extends ReadonlyArray<infer Element> ? Element : Type;
1593
1594type UpdateOptionalId<T> = T extends { _id?: any } ? OptionalId<T> : T;
1595
1596export type SortValues = -1 | 1;
1597
1598/** https://docs.mongodb.com/manual/reference/operator/aggregation/meta/#proj._S_meta */
1599export type MetaSortOperators = 'textScore' | 'indexKey';
1600
1601export type MetaProjectionOperators =
1602 | MetaSortOperators
1603 /** Only for Atlas Search https://docs.atlas.mongodb.com/reference/atlas-search/scoring/ */
1604 | 'searchScore'
1605 /** Only for Atlas Search https://docs.atlas.mongodb.com/reference/atlas-search/highlighting/ */
1606 | 'searchHighlights';
1607
1608export type SchemaMember<T, V> = { [P in keyof T]?: V } | { [key: string]: V };
1609
1610export type SortOptionObject<T> = SchemaMember<T, number | { $meta?: MetaSortOperators }>;
1611
1612export type AddToSetOperators<Type> = {
1613 $each: Type;
1614};
1615
1616export type ArrayOperator<Type> = {
1617 $each: Type;
1618 $slice?: number;
1619 $position?: number;
1620 $sort?: SortValues | Record<string, SortValues>;
1621};
1622
1623export type SetFields<TSchema> = ({
1624 readonly [key in KeysOfAType<TSchema, ReadonlyArray<any> | undefined>]?:
1625 | UpdateOptionalId<Unpacked<TSchema[key]>>
1626 | AddToSetOperators<Array<UpdateOptionalId<Unpacked<TSchema[key]>>>>;
1627} &
1628 NotAcceptedFields<TSchema, ReadonlyArray<any> | undefined>) & {
1629 readonly [key: string]: AddToSetOperators<any> | any;
1630};
1631
1632export type PushOperator<TSchema> = ({
1633 readonly [key in KeysOfAType<TSchema, ReadonlyArray<any>>]?:
1634 | UpdateOptionalId<Unpacked<TSchema[key]>>
1635 | ArrayOperator<Array<UpdateOptionalId<Unpacked<TSchema[key]>>>>;
1636} &
1637 NotAcceptedFields<TSchema, ReadonlyArray<any>>) & {
1638 readonly [key: string]: ArrayOperator<any> | any;
1639};
1640
1641export type PullOperator<TSchema> = ({
1642 readonly [key in KeysOfAType<TSchema, ReadonlyArray<any>>]?:
1643 | Partial<Unpacked<TSchema[key]>>
1644 | ObjectQuerySelector<Unpacked<TSchema[key]>>;
1645} &
1646 NotAcceptedFields<TSchema, ReadonlyArray<any>>) & {
1647 readonly [key: string]: QuerySelector<any> | any;
1648};
1649
1650export type PullAllOperator<TSchema> = ({
1651 readonly [key in KeysOfAType<TSchema, ReadonlyArray<any>>]?: TSchema[key];
1652} &
1653 NotAcceptedFields<TSchema, ReadonlyArray<any>>) & {
1654 readonly [key: string]: any[];
1655};
1656
1657/** https://docs.mongodb.com/manual/reference/operator/update */
1658export type UpdateQuery<TSchema> = {
1659 /** https://docs.mongodb.com/manual/reference/operator/update-field/ */
1660 $currentDate?: OnlyFieldsOfType<TSchema, Date, true | { $type: 'date' | 'timestamp' }>;
1661 $inc?: OnlyFieldsOfType<TSchema, NumericTypes | undefined>;
1662 $min?: MatchKeysAndValues<TSchema>;
1663 $max?: MatchKeysAndValues<TSchema>;
1664 $mul?: OnlyFieldsOfType<TSchema, NumericTypes | undefined>;
1665 $rename?: { [key: string]: string };
1666 $set?: MatchKeysAndValues<TSchema>;
1667 $setOnInsert?: MatchKeysAndValues<TSchema>;
1668 $unset?: OnlyFieldsOfType<TSchema, any, '' | 1 | true>;
1669
1670 /** https://docs.mongodb.com/manual/reference/operator/update-array/ */
1671 $addToSet?: SetFields<TSchema>;
1672 $pop?: OnlyFieldsOfType<TSchema, ReadonlyArray<any>, 1 | -1>;
1673 $pull?: PullOperator<TSchema>;
1674 $push?: PushOperator<TSchema>;
1675 $pullAll?: PullAllOperator<TSchema>;
1676
1677 /** https://docs.mongodb.com/manual/reference/operator/update-bitwise/ */
1678 $bit?: {
1679 [key: string]: { [key in 'and' | 'or' | 'xor']?: number };
1680 };
1681};
1682
1683/** https://docs.mongodb.com/manual/reference/operator/query/type/#available-types */
1684export enum BSONType {
1685 Double = 1,
1686 String,
1687 Object,
1688 Array,
1689 BinData,
1690 /** @deprecated */
1691 Undefined,
1692 ObjectId,
1693 Boolean,
1694 Date,
1695 Null,
1696 Regex,
1697 /** @deprecated */
1698 DBPointer,
1699 JavaScript,
1700 /** @deprecated */
1701 Symbol,
1702 JavaScriptWithScope,
1703 Int,
1704 Timestamp,
1705 Long,
1706 Decimal,
1707 MinKey = -1,
1708 MaxKey = 127,
1709}
1710
1711type BSONTypeAlias =
1712 | 'number'
1713 | 'double'
1714 | 'string'
1715 | 'object'
1716 | 'array'
1717 | 'binData'
1718 | 'undefined'
1719 | 'objectId'
1720 | 'bool'
1721 | 'date'
1722 | 'null'
1723 | 'regex'
1724 | 'dbPointer'
1725 | 'javascript'
1726 | 'symbol'
1727 | 'javascriptWithScope'
1728 | 'int'
1729 | 'timestamp'
1730 | 'long'
1731 | 'decimal'
1732 | 'minKey'
1733 | 'maxKey';
1734
1735/** https://docs.mongodb.com/manual/reference/operator/query-bitwise */
1736type BitwiseQuery =
1737 | number /** <numeric bitmask> */
1738 | Binary /** <BinData bitmask> */
1739 | number[]; /** [ <position1>, <position2>, ... ] */
1740
1741// we can search using alternative types in mongodb e.g.
1742// string types can be searched using a regex in mongo
1743// array types can be searched using their element type
1744type RegExpForString<T> = T extends string ? RegExp | T : T;
1745type MongoAltQuery<T> = T extends ReadonlyArray<infer U> ? T | RegExpForString<U> : RegExpForString<T>;
1746
1747/** https://docs.mongodb.com/manual/reference/operator/query/#query-selectors */
1748export type QuerySelector<T> = {
1749 // Comparison
1750 $eq?: T;
1751 $gt?: T;
1752 $gte?: T;
1753 $in?: T[];
1754 $lt?: T;
1755 $lte?: T;
1756 $ne?: T;
1757 $nin?: T[];
1758 // Logical
1759 $not?: T extends string ? QuerySelector<T> | RegExp : QuerySelector<T>;
1760 // Element
1761 /**
1762 * When `true`, `$exists` matches the documents that contain the field,
1763 * including documents where the field value is null.
1764 */
1765 $exists?: boolean;
1766 $type?: BSONType | BSONTypeAlias;
1767 // Evaluation
1768 $expr?: any;
1769 $jsonSchema?: any;
1770 $mod?: T extends number ? [number, number] : never;
1771 $regex?: T extends string ? RegExp | string : never;
1772 $options?: T extends string ? string : never;
1773 // Geospatial
1774 // TODO: define better types for geo queries
1775 $geoIntersects?: { $geometry: object };
1776 $geoWithin?: object;
1777 $near?: object;
1778 $nearSphere?: object;
1779 $maxDistance?: number;
1780 // Array
1781 // TODO: define better types for $all and $elemMatch
1782 $all?: T extends ReadonlyArray<infer U> ? any[] : never;
1783 $elemMatch?: T extends ReadonlyArray<infer U> ? object : never;
1784 $size?: T extends ReadonlyArray<infer U> ? number : never;
1785 // Bitwise
1786 $bitsAllClear?: BitwiseQuery;
1787 $bitsAllSet?: BitwiseQuery;
1788 $bitsAnyClear?: BitwiseQuery;
1789 $bitsAnySet?: BitwiseQuery;
1790};
1791
1792export type RootQuerySelector<T> = {
1793 /** https://docs.mongodb.com/manual/reference/operator/query/and/#op._S_and */
1794 $and?: Array<FilterQuery<T>>;
1795 /** https://docs.mongodb.com/manual/reference/operator/query/nor/#op._S_nor */
1796 $nor?: Array<FilterQuery<T>>;
1797 /** https://docs.mongodb.com/manual/reference/operator/query/or/#op._S_or */
1798 $or?: Array<FilterQuery<T>>;
1799 /** https://docs.mongodb.com/manual/reference/operator/query/text */
1800 $text?: {
1801 $search: string;
1802 $language?: string;
1803 $caseSensitive?: boolean;
1804 $diacraticSensitive?: boolean;
1805 };
1806 /** https://docs.mongodb.com/manual/reference/operator/query/where/#op._S_where */
1807 $where?: string | Function;
1808 /** https://docs.mongodb.com/manual/reference/operator/query/comment/#op._S_comment */
1809 $comment?: string;
1810 // we could not find a proper TypeScript generic to support nested queries e.g. 'user.friends.name'
1811 // this will mark all unrecognized properties as any (including nested queries)
1812 [key: string]: any;
1813};
1814
1815export type ObjectQuerySelector<T> = T extends object ? { [key in keyof T]?: QuerySelector<T[key]> } : QuerySelector<T>;
1816
1817export type Condition<T> = MongoAltQuery<T> | QuerySelector<MongoAltQuery<T>>;
1818
1819export type FilterQuery<T> = {
1820 [P in keyof T]?: Condition<T[P]>;
1821} &
1822 RootQuerySelector<T>;
1823
1824/** https://docs.mongodb.com/manual/reference/method/db.collection.bulkWrite/#insertone */
1825export type BulkWriteInsertOneOperation<TSchema> = {
1826 insertOne: {
1827 document: OptionalId<TSchema>;
1828 };
1829};
1830
1831/** https://docs.mongodb.com/manual/reference/method/db.collection.bulkWrite/#updateone-and-updatemany */
1832export type BulkWriteUpdateOperation<TSchema> = {
1833 arrayFilters?: object[];
1834 collation?: object;
1835 hint?: string | object;
1836 filter: FilterQuery<TSchema>;
1837 update: UpdateQuery<TSchema>;
1838 upsert?: boolean;
1839};
1840export type BulkWriteUpdateOneOperation<TSchema> = {
1841 updateOne: BulkWriteUpdateOperation<TSchema>;
1842};
1843export type BulkWriteUpdateManyOperation<TSchema> = {
1844 updateMany: BulkWriteUpdateOperation<TSchema>;
1845};
1846
1847/** https://docs.mongodb.com/manual/reference/method/db.collection.bulkWrite/#replaceone */
1848export type BulkWriteReplaceOneOperation<TSchema> = {
1849 replaceOne: {
1850 collation?: object;
1851 hint?: string | object;
1852 filter: FilterQuery<TSchema>;
1853 replacement: TSchema;
1854 upsert?: boolean;
1855 };
1856};
1857
1858/** https://docs.mongodb.com/manual/reference/method/db.collection.bulkWrite/#deleteone-and-deletemany */
1859export type BulkWriteDeleteOperation<TSchema> = {
1860 collation?: object;
1861 filter: FilterQuery<TSchema>;
1862};
1863export type BulkWriteDeleteOneOperation<TSchema> = {
1864 deleteOne: BulkWriteDeleteOperation<TSchema>;
1865};
1866export type BulkWriteDeleteManyOperation<TSchema> = {
1867 deleteMany: BulkWriteDeleteOperation<TSchema>;
1868};
1869
1870/** http://mongodb.github.io/node-mongodb-native/3.0/api/Collection.html#bulkWrite */
1871export type BulkWriteOperation<TSchema> =
1872 | BulkWriteInsertOneOperation<TSchema>
1873 | BulkWriteUpdateOneOperation<TSchema>
1874 | BulkWriteUpdateManyOperation<TSchema>
1875 | BulkWriteReplaceOneOperation<TSchema>
1876 | BulkWriteDeleteOneOperation<TSchema>
1877 | BulkWriteDeleteManyOperation<TSchema>;
1878
1879/** http://docs.mongodb.org/manual/reference/command/collStats/ */
1880export interface CollStats {
1881 /**
1882 * Namespace.
1883 */
1884 ns: string;
1885 /**
1886 * Number of documents.
1887 */
1888 count: number;
1889 /**
1890 * Collection size in bytes.
1891 */
1892 size: number;
1893 /**
1894 * Average object size in bytes.
1895 */
1896 avgObjSize: number;
1897 /**
1898 * (Pre)allocated space for the collection in bytes.
1899 */
1900 storageSize: number;
1901 /**
1902 * Number of extents (contiguously allocated chunks of datafile space).
1903 */
1904 numExtents: number;
1905 /**
1906 * Number of indexes.
1907 */
1908 nindexes: number;
1909 /**
1910 * Size of the most recently created extent in bytes.
1911 */
1912 lastExtentSize: number;
1913 /**
1914 * Padding can speed up updates if documents grow.
1915 */
1916 paddingFactor: number;
1917 /**
1918 * A number that indicates the user-set flags on the collection. userFlags only appears when using the mmapv1 storage engine.
1919 */
1920 userFlags?: number;
1921 /**
1922 * Total index size in bytes.
1923 */
1924 totalIndexSize: number;
1925 /**
1926 * Size of specific indexes in bytes.
1927 */
1928 indexSizes: {
1929 _id_: number;
1930 [index: string]: number;
1931 };
1932 /**
1933 * `true` if the collection is capped.
1934 */
1935 capped: boolean;
1936 /**
1937 * The maximum number of documents that may be present in a capped collection.
1938 */
1939 max: number;
1940 /**
1941 * The maximum size of a capped collection.
1942 */
1943 maxSize: number;
1944 wiredTiger?: WiredTigerData;
1945 indexDetails?: any;
1946 ok: number;
1947}
1948
1949export interface WiredTigerData {
1950 LSM: {
1951 'bloom filter false positives': number;
1952 'bloom filter hits': number;
1953 'bloom filter misses': number;
1954 'bloom filter pages evicted from cache': number;
1955 'bloom filter pages read into cache': number;
1956 'bloom filters in the LSM tree': number;
1957 'chunks in the LSM tree': number;
1958 'highest merge generation in the LSM tree': number;
1959 'queries that could have benefited from a Bloom filter that did not exist': number;
1960 'sleep for LSM checkpoint throttle': number;
1961 'sleep for LSM merge throttle': number;
1962 'total size of bloom filters': number;
1963 };
1964 'block-manager': {
1965 'allocations requiring file extension': number;
1966 'blocks allocated': number;
1967 'blocks freed': number;
1968 'checkpoint size': number;
1969 'file allocation unit size': number;
1970 'file bytes available for reuse': number;
1971 'file magic number': number;
1972 'file major version number': number;
1973 'file size in bytes': number;
1974 'minor version number': number;
1975 };
1976 btree: {
1977 'btree checkpoint generation': number;
1978 'column-store fixed-size leaf pages': number;
1979 'column-store internal pages': number;
1980 'column-store variable-size RLE encoded values': number;
1981 'column-store variable-size deleted values': number;
1982 'column-store variable-size leaf pages': number;
1983 'fixed-record size': number;
1984 'maximum internal page key size': number;
1985 'maximum internal page size': number;
1986 'maximum leaf page key size': number;
1987 'maximum leaf page size': number;
1988 'maximum leaf page value size': number;
1989 'maximum tree depth': number;
1990 'number of key/value pairs': number;
1991 'overflow pages': number;
1992 'pages rewritten by compaction': number;
1993 'row-store internal pages': number;
1994 'row-store leaf pages': number;
1995 };
1996 cache: {
1997 'bytes currently in the cache': number;
1998 'bytes read into cache': number;
1999 'bytes written from cache': number;
2000 'checkpoint blocked page eviction': number;
2001 'data source pages selected for eviction unable to be evicted': number;
2002 'hazard pointer blocked page eviction': number;
2003 'in-memory page passed criteria to be split': number;
2004 'in-memory page splits': number;
2005 'internal pages evicted': number;
2006 'internal pages split during eviction': number;
2007 'leaf pages split during eviction': number;
2008 'modified pages evicted': number;
2009 'overflow pages read into cache': number;
2010 'overflow values cached in memory': number;
2011 'page split during eviction deepened the tree': number;
2012 'page written requiring lookaside records': number;
2013 'pages read into cache': number;
2014 'pages read into cache requiring lookaside entries': number;
2015 'pages requested from the cache': number;
2016 'pages written from cache': number;
2017 'pages written requiring in-memory restoration': number;
2018 'tracked dirty bytes in the cache': number;
2019 'unmodified pages evicted': number;
2020 };
2021 cache_walk: {
2022 'Average difference between current eviction generation when the page was last considered': number;
2023 'Average on-disk page image size seen': number;
2024 'Clean pages currently in cache': number;
2025 'Current eviction generation': number;
2026 'Dirty pages currently in cache': number;
2027 'Entries in the root page': number;
2028 'Internal pages currently in cache': number;
2029 'Leaf pages currently in cache': number;
2030 'Maximum difference between current eviction generation when the page was last considered': number;
2031 'Maximum page size seen': number;
2032 'Minimum on-disk page image size seen': number;
2033 'On-disk page image sizes smaller than a single allocation unit': number;
2034 'Pages created in memory and never written': number;
2035 'Pages currently queued for eviction': number;
2036 'Pages that could not be queued for eviction': number;
2037 'Refs skipped during cache traversal': number;
2038 'Size of the root page': number;
2039 'Total number of pages currently in cache': number;
2040 };
2041 compression: {
2042 'compressed pages read': number;
2043 'compressed pages written': number;
2044 'page written failed to compress': number;
2045 'page written was too small to compress': number;
2046 'raw compression call failed, additional data available': number;
2047 'raw compression call failed, no additional data available': number;
2048 'raw compression call succeeded': number;
2049 };
2050 cursor: {
2051 'bulk-loaded cursor-insert calls': number;
2052 'create calls': number;
2053 'cursor-insert key and value bytes inserted': number;
2054 'cursor-remove key bytes removed': number;
2055 'cursor-update value bytes updated': number;
2056 'insert calls': number;
2057 'next calls': number;
2058 'prev calls': number;
2059 'remove calls': number;
2060 'reset calls': number;
2061 'restarted searches': number;
2062 'search calls': number;
2063 'search near calls': number;
2064 'truncate calls': number;
2065 'update calls': number;
2066 };
2067 reconciliation: {
2068 'dictionary matches': number;
2069 'fast-path pages deleted': number;
2070 'internal page key bytes discarded using suffix compression': number;
2071 'internal page multi-block writes': number;
2072 'internal-page overflow keys': number;
2073 'leaf page key bytes discarded using prefix compression': number;
2074 'leaf page multi-block writes': number;
2075 'leaf-page overflow keys': number;
2076 'maximum blocks required for a page': number;
2077 'overflow values written': number;
2078 'page checksum matches': number;
2079 'page reconciliation calls': number;
2080 'page reconciliation calls for eviction': number;
2081 'pages deleted': number;
2082 };
2083}
2084
2085/** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#aggregate */
2086export interface CollectionAggregationOptions {
2087 readPreference?: ReadPreferenceOrMode;
2088 /**
2089 * Return the query as cursor, on 2.6 > it returns as a real cursor
2090 * on pre 2.6 it returns as an emulated cursor.
2091 */
2092 cursor?: { batchSize?: number };
2093 /**
2094 * Explain returns the aggregation execution plan (requires mongodb 2.6 >).
2095 */
2096 explain?: boolean;
2097 /**
2098 * Lets the server know if it can use disk to store
2099 * temporary results for the aggregation (requires mongodb 2.6 >).
2100 */
2101 allowDiskUse?: boolean;
2102 /**
2103 * specifies a cumulative time limit in milliseconds for processing operations
2104 * on the cursor. MongoDB interrupts the operation at the earliest following interrupt point.
2105 */
2106 maxTimeMS?: number;
2107 /**
2108 * Allow driver to bypass schema validation in MongoDB 3.2 or higher.
2109 */
2110 bypassDocumentValidation?: boolean;
2111 hint?: string | object;
2112 raw?: boolean;
2113 promoteLongs?: boolean;
2114 promoteValues?: boolean;
2115 promoteBuffers?: boolean;
2116 collation?: CollationDocument;
2117 comment?: string;
2118 session?: ClientSession;
2119}
2120
2121/** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#insertMany */
2122export interface CollectionInsertManyOptions extends CommonOptions {
2123 /**
2124 * Serialize functions on any object.
2125 */
2126 serializeFunctions?: boolean;
2127 /**
2128 * Force server to assign _id values instead of driver.
2129 */
2130 forceServerObjectId?: boolean;
2131 /**
2132 * Allow driver to bypass schema validation in MongoDB 3.2 or higher.
2133 */
2134 bypassDocumentValidation?: boolean;
2135 /**
2136 * If true, when an insert fails, don't execute the remaining writes. If false, continue with remaining inserts when one fails.
2137 */
2138 ordered?: boolean;
2139}
2140
2141/** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#bulkWrite */
2142export interface CollectionBulkWriteOptions extends CommonOptions {
2143 /**
2144 * Serialize functions on any object.
2145 */
2146 serializeFunctions?: boolean;
2147 /**
2148 * Execute write operation in ordered or unordered fashion.
2149 */
2150 ordered?: boolean;
2151 /**
2152 * Allow driver to bypass schema validation in MongoDB 3.2 or higher.
2153 */
2154 bypassDocumentValidation?: boolean;
2155 //Force server to assign _id values instead of driver.
2156 forceServerObjectId?: boolean;
2157}
2158
2159/** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#~BulkWriteOpResult */
2160export interface BulkWriteOpResultObject {
2161 insertedCount?: number;
2162 matchedCount?: number;
2163 modifiedCount?: number;
2164 deletedCount?: number;
2165 upsertedCount?: number;
2166 insertedIds?: { [index: number]: any };
2167 upsertedIds?: { [index: number]: any };
2168 result?: any;
2169}
2170
2171/** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#count */
2172export interface MongoCountPreferences {
2173 /**
2174 * The limit of documents to count.
2175 */
2176 limit?: number;
2177 /**
2178 * The number of documents to skip for the count.
2179 */
2180 skip?: number;
2181 /**
2182 * An index name hint for the query.
2183 */
2184 hint?: string;
2185 /**
2186 * The preferred read preference
2187 */
2188 readPreference?: ReadPreferenceOrMode;
2189 /**
2190 * Number of miliseconds to wait before aborting the query.
2191 */
2192 maxTimeMS?: number;
2193 /**
2194 * Optional session to use for this operation
2195 */
2196 session?: ClientSession;
2197}
2198
2199/** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#distinct */
2200export interface MongoDistinctPreferences {
2201 /**
2202 * The preferred read preference
2203 */
2204 readPreference?: ReadPreferenceOrMode;
2205 /**
2206 * Number of miliseconds to wait before aborting the query.
2207 */
2208 maxTimeMS?: number;
2209 /**
2210 * Optional session to use for this operation
2211 */
2212 session?: ClientSession;
2213}
2214
2215/** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#~deleteWriteOpResult */
2216export interface DeleteWriteOpResultObject {
2217 //The raw result returned from MongoDB, field will vary depending on server version.
2218 result: {
2219 //Is 1 if the command executed correctly.
2220 ok?: number;
2221 //The total count of documents deleted.
2222 n?: number;
2223 };
2224 //The connection object used for the operation.
2225 connection?: any;
2226 //The number of documents deleted.
2227 deletedCount?: number;
2228}
2229
2230/** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#~findAndModifyWriteOpResult */
2231export interface FindAndModifyWriteOpResultObject<TSchema> {
2232 //Document returned from findAndModify command.
2233 value?: TSchema;
2234 //The raw lastErrorObject returned from the command.
2235 lastErrorObject?: any;
2236 //Is 1 if the command executed correctly.
2237 ok?: number;
2238}
2239
2240/** http://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html#findOneAndReplace */
2241export interface FindOneAndReplaceOption<T> extends CommonOptions {
2242 projection?: SchemaMember<T, ProjectionOperators | number | boolean | any>;
2243 sort?: SortOptionObject<T>;
2244 maxTimeMS?: number;
2245 upsert?: boolean;
2246 returnOriginal?: boolean;
2247 collation?: CollationDocument;
2248}
2249
2250/** https://docs.mongodb.com/manual/reference/operator/projection/ */
2251export interface ProjectionOperators {
2252 /** https://docs.mongodb.com/manual/reference/operator/projection/elemMatch/#proj._S_elemMatch */
2253 $elemMatch?: object;
2254 /** https://docs.mongodb.com/manual/reference/operator/projection/slice/#proj._S_slice */
2255 $slice?: number | [number, number];
2256 $meta?: MetaProjectionOperators;
2257}
2258
2259/** http://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html#findOneAndUpdate */
2260export interface FindOneAndUpdateOption<T> extends FindOneAndReplaceOption<T> {
2261 arrayFilters?: object[];
2262}
2263
2264/** http://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html#findOneAndDelete */
2265export interface FindOneAndDeleteOption<T> {
2266 projection?: SchemaMember<T, ProjectionOperators | number | boolean | any>;
2267 sort?: SortOptionObject<T>;
2268 maxTimeMS?: number;
2269 session?: ClientSession;
2270 collation?: CollationDocument;
2271}
2272
2273/** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#geoHaystackSearch */
2274export interface GeoHaystackSearchOptions {
2275 readPreference?: ReadPreferenceOrMode;
2276 maxDistance?: number;
2277 search?: object;
2278 limit?: number;
2279 session?: ClientSession;
2280}
2281
2282/** http://mongodb.github.io/node-mongodb-native/3.1/api/Code.html */
2283export class Code {
2284 constructor(code: string | Function, scope?: object);
2285 code: string | Function;
2286 scope: any;
2287}
2288
2289/** http://mongodb.github.io/node-mongodb-native/3.1/api/OrderedBulkOperation.html */
2290export interface OrderedBulkOperation {
2291 length: number;
2292 /** http://mongodb.github.io/node-mongodb-native/3.1/api/OrderedBulkOperation.html#execute */
2293 execute(callback: MongoCallback<BulkWriteResult>): void;
2294 execute(options?: FSyncOptions): Promise<BulkWriteResult>;
2295 execute(options: FSyncOptions, callback: MongoCallback<BulkWriteResult>): void;
2296 /** http://mongodb.github.io/node-mongodb-native/3.1/api/OrderedBulkOperation.html#find */
2297 find(selector: object): FindOperatorsOrdered;
2298 /** http://mongodb.github.io/node-mongodb-native/3.1/api/OrderedBulkOperation.html#insert */
2299 insert(doc: object): OrderedBulkOperation;
2300}
2301
2302/** https://docs.mongodb.com/manual/reference/method/BulkWriteResult/index.html#BulkWriteResult.upserted */
2303export interface BulkWriteResultUpsertedIdObject {
2304 index: number;
2305 _id: ObjectId;
2306}
2307
2308/** http://mongodb.github.io/node-mongodb-native/3.5/api/BulkWriteResult.html */
2309export interface BulkWriteResult {
2310 /**
2311 * Evaluates to `true` if the bulk operation correctly executes
2312 */
2313 ok: boolean;
2314
2315 /**
2316 * The number of documents inserted, excluding upserted documents.
2317 *
2318 * @see {@link nUpserted} for the number of documents inserted through an upsert.
2319 */
2320 nInserted: number;
2321
2322 /**
2323 * The number of documents selected for update.
2324 *
2325 * If the update operation results in no change to the document,
2326 * e.g. `$set` expression updates the value to the current value,
2327 * {@link nMatched} can be greater than {@link nModified}.
2328 */
2329 nMatched: number;
2330
2331 /**
2332 * The number of existing documents updated.
2333 *
2334 * If the update/replacement operation results in no change to the document,
2335 * such as setting the value of the field to its current value,
2336 * {@link nModified} can be less than {@link nMatched}
2337 */
2338 nModified: number;
2339
2340 /**
2341 * The number of documents inserted by an
2342 * [upsert]{@link https://docs.mongodb.com/manual/reference/method/db.collection.update/#upsert-parameter}.
2343 */
2344 nUpserted: number;
2345
2346 /**
2347 * The number of documents removed.
2348 */
2349 nRemoved: number;
2350
2351 // Returns an array of all inserted ids
2352 getInsertedIds(): object[];
2353 // Retrieve lastOp if available
2354 getLastOp(): object;
2355 // Returns raw internal result
2356 getRawResponse(): object;
2357
2358 /**
2359 * Returns the upserted id at the given index
2360 * @param index the number of the upserted id to return, returns `undefined` if no result for passed in index
2361 */
2362 getUpsertedIdAt(index: number): BulkWriteResultUpsertedIdObject;
2363
2364 // Returns an array of all upserted ids
2365 getUpsertedIds(): BulkWriteResultUpsertedIdObject[];
2366 // Retrieve the write concern error if any
2367 getWriteConcernError(): WriteConcernError;
2368
2369 /**
2370 * Returns a specific write error object
2371 * @param index of the write error to return, returns `null` if there is no result for passed in index
2372 */
2373 getWriteErrorAt(index: number): WriteError;
2374
2375 // Returns the number of write errors off the bulk operation
2376 getWriteErrorCount(): number;
2377 // Retrieve all write errors
2378 getWriteErrors(): object[];
2379 // Returns `true` if the bulk operation contains a write error
2380 hasWriteErrors(): boolean;
2381}
2382
2383/** http://mongodb.github.io/node-mongodb-native/3.1/api/WriteError.html */
2384export interface WriteError {
2385 //Write concern error code.
2386 code: number;
2387 //Write concern error original bulk operation index.
2388 index: number;
2389 //Write concern error message.
2390 errmsg: string;
2391}
2392
2393/** http://mongodb.github.io/node-mongodb-native/3.1/api/WriteConcernError.html */
2394export interface WriteConcernError {
2395 //Write concern error code.
2396 code: number;
2397 //Write concern error message.
2398 errmsg: string;
2399}
2400
2401/** http://mongodb.github.io/node-mongodb-native/3.1/api/FindOperatorsOrdered.html */
2402export interface FindOperatorsOrdered {
2403 delete(): OrderedBulkOperation;
2404 deleteOne(): OrderedBulkOperation;
2405 replaceOne(doc: object): OrderedBulkOperation;
2406 update(doc: object): OrderedBulkOperation;
2407 updateOne(doc: object): OrderedBulkOperation;
2408 upsert(): FindOperatorsOrdered;
2409}
2410
2411/** http://mongodb.github.io/node-mongodb-native/3.1/api/UnorderedBulkOperation.html */
2412export interface UnorderedBulkOperation {
2413 /** http://mongodb.github.io/node-mongodb-native/3.1/api/lib_bulk_unordered.js.html line 339 */
2414 length: number;
2415 /** http://mongodb.github.io/node-mongodb-native/3.1/api/UnorderedBulkOperation.html#execute */
2416 execute(callback: MongoCallback<BulkWriteResult>): void;
2417 execute(options?: FSyncOptions): Promise<BulkWriteResult>;
2418 execute(options: FSyncOptions, callback: MongoCallback<BulkWriteResult>): void;
2419 /** http://mongodb.github.io/node-mongodb-native/3.1/api/UnorderedBulkOperation.html#find */
2420 find(selector: object): FindOperatorsUnordered;
2421 /** http://mongodb.github.io/node-mongodb-native/3.1/api/UnorderedBulkOperation.html#insert */
2422 insert(doc: object): UnorderedBulkOperation;
2423}
2424
2425/** http://mongodb.github.io/node-mongodb-native/3.1/api/FindOperatorsUnordered.html */
2426export interface FindOperatorsUnordered {
2427 length: number;
2428 remove(): UnorderedBulkOperation;
2429 removeOne(): UnorderedBulkOperation;
2430 replaceOne(doc: object): UnorderedBulkOperation;
2431 update(doc: object): UnorderedBulkOperation;
2432 updateOne(doc: object): UnorderedBulkOperation;
2433 upsert(): FindOperatorsUnordered;
2434}
2435
2436/** http://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html#findOne */
2437export interface FindOneOptions<T> {
2438 limit?: number;
2439 sort?: Array<[string, number]> | SortOptionObject<T>;
2440 projection?: SchemaMember<T, ProjectionOperators | number | boolean | any>;
2441 /**
2442 * @deprecated Use options.projection instead
2443 */
2444 fields?: { [P in keyof T]: boolean | number };
2445 skip?: number;
2446 hint?: object;
2447 explain?: boolean;
2448 snapshot?: boolean;
2449 timeout?: boolean;
2450 tailable?: boolean;
2451 awaitData?: boolean;
2452 batchSize?: number;
2453 returnKey?: boolean;
2454 maxScan?: number;
2455 min?: number;
2456 max?: number;
2457 showDiskLoc?: boolean;
2458 comment?: string;
2459 raw?: boolean;
2460 promoteLongs?: boolean;
2461 promoteValues?: boolean;
2462 promoteBuffers?: boolean;
2463 readPreference?: ReadPreferenceOrMode;
2464 partial?: boolean;
2465 maxTimeMS?: number;
2466 collation?: CollationDocument;
2467 session?: ClientSession;
2468}
2469
2470/** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#insertOne */
2471export interface CollectionInsertOneOptions extends CommonOptions {
2472 /**
2473 * Serialize functions on any object.
2474 */
2475 serializeFunctions?: boolean;
2476 //Force server to assign _id values instead of driver.
2477 forceServerObjectId?: boolean;
2478 //Allow driver to bypass schema validation in MongoDB 3.2 or higher.
2479 bypassDocumentValidation?: boolean;
2480}
2481
2482/** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#~insertWriteOpResult */
2483export interface InsertWriteOpResult<TSchema extends { _id: any }> {
2484 insertedCount: number;
2485 ops: TSchema[];
2486 insertedIds: { [key: number]: TSchema['_id'] };
2487 connection: any;
2488 result: { ok: number; n: number };
2489}
2490
2491/** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#~insertOneWriteOpResult */
2492export interface InsertOneWriteOpResult<TSchema extends { _id: any }> {
2493 insertedCount: number;
2494 ops: TSchema[];
2495 insertedId: TSchema['_id'];
2496 connection: any;
2497 result: { ok: number; n: number };
2498}
2499
2500/** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#parallelCollectionScan */
2501export interface ParallelCollectionScanOptions {
2502 readPreference?: ReadPreferenceOrMode;
2503 batchSize?: number;
2504 numCursors?: number;
2505 raw?: boolean;
2506 session?: ClientSession;
2507}
2508
2509/** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#replaceOne */
2510export interface ReplaceOneOptions extends CommonOptions {
2511 upsert?: boolean;
2512 bypassDocumentValidation?: boolean;
2513}
2514
2515/** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#updateOne */
2516export interface UpdateOneOptions extends ReplaceOneOptions {
2517 arrayFilters?: object[];
2518}
2519
2520/** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#updateMany */
2521export interface UpdateManyOptions extends CommonOptions {
2522 upsert?: boolean;
2523 arrayFilters?: object[];
2524}
2525
2526/** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#~updateWriteOpResult */
2527export interface UpdateWriteOpResult {
2528 result: { ok: number; n: number; nModified: number };
2529 connection: any;
2530 matchedCount: number;
2531 modifiedCount: number;
2532 upsertedCount: number;
2533 upsertedId: { _id: ObjectId };
2534}
2535
2536/** https://github.com/mongodb/node-mongodb-native/blob/2.2/lib/collection.js#L957 */
2537export interface ReplaceWriteOpResult extends UpdateWriteOpResult {
2538 ops: any[];
2539}
2540
2541/** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#mapReduce */
2542export interface MapReduceOptions {
2543 readPreference?: ReadPreferenceOrMode;
2544 out?: object;
2545 query?: object;
2546 sort?: object;
2547 limit?: number;
2548 keeptemp?: boolean;
2549 finalize?: Function | string;
2550 scope?: object;
2551 jsMode?: boolean;
2552 verbose?: boolean;
2553 bypassDocumentValidation?: boolean;
2554 session?: ClientSession;
2555}
2556
2557export type CollectionMapFunction<TSchema> = (this: TSchema) => void;
2558
2559export type CollectionReduceFunction<TKey, TValue> = (key: TKey, values: TValue[]) => TValue;
2560
2561/** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#~WriteOpResult */
2562export interface WriteOpResult {
2563 ops: any[];
2564 connection: any;
2565 result: any;
2566}
2567
2568/** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#~resultCallback */
2569export type CursorResult = object | null | boolean;
2570
2571type Default = any;
2572type DefaultSchema = any;
2573
2574/** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html */
2575export class Cursor<T = Default> extends Readable {
2576 [Symbol.asyncIterator](): AsyncIterableIterator<T>;
2577 sortValue: string;
2578 timeout: boolean;
2579 readPreference: ReadPreference;
2580 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#addCursorFlag */
2581 addCursorFlag(flag: string, value: boolean): Cursor<T>;
2582 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#addQueryModifier */
2583 addQueryModifier(name: string, value: boolean): Cursor<T>;
2584 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#batchSize */
2585 batchSize(value: number): Cursor<T>;
2586 bufferedCount(): number;
2587 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#clone */
2588 clone(): Cursor<T>; // still returns the same type
2589 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#close */
2590 close(): Promise<CursorResult>;
2591 close(callback: MongoCallback<CursorResult>): void;
2592 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#collation */
2593 collation(value: CollationDocument): Cursor<T>;
2594 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#comment */
2595 comment(value: string): Cursor<T>;
2596 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#count */
2597 count(callback: MongoCallback<number>): void;
2598 count(applySkipLimit: boolean, callback: MongoCallback<number>): void;
2599 count(options: CursorCommentOptions, callback: MongoCallback<number>): void;
2600 count(applySkipLimit: boolean, options: CursorCommentOptions, callback: MongoCallback<number>): void;
2601 count(applySkipLimit?: boolean, options?: CursorCommentOptions): Promise<number>;
2602 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#explain */
2603 explain(): Promise<CursorResult>;
2604 explain(callback: MongoCallback<CursorResult>): void;
2605 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#filter */
2606 filter(filter: object): Cursor<T>;
2607 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#forEach */
2608 forEach(iterator: IteratorCallback<T>, callback: EndCallback): void;
2609 forEach(iterator: IteratorCallback<T>): Promise<void>;
2610 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#hasNext */
2611 hasNext(): Promise<boolean>;
2612 hasNext(callback: MongoCallback<boolean>): void;
2613 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#hint */
2614 hint(hint: string | object): Cursor<T>;
2615 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#isClosed */
2616 isClosed(): boolean;
2617 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#limit */
2618 limit(value: number): Cursor<T>;
2619 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#map */
2620 map<U>(transform: (document: T) => U): Cursor<U>;
2621 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#max */
2622 max(max: object): Cursor<T>;
2623 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#maxAwaitTimeMS */
2624 maxAwaitTimeMS(value: number): Cursor<T>;
2625 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#maxScan */
2626 maxScan(maxScan: object): Cursor<T>;
2627 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#maxTimeMS */
2628 maxTimeMS(value: number): Cursor<T>;
2629 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#min */
2630 min(min: object): Cursor<T>;
2631 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#next */
2632 next(): Promise<T | null>;
2633 next(callback: MongoCallback<T | null>): void;
2634 /** http://mongodb.github.io/node-mongodb-native/3.6/api/Cursor.html#project */
2635 project(value: SchemaMember<T, ProjectionOperators | number | boolean | any>): Cursor<T>;
2636 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#read */
2637 read(size: number): string | Buffer | void;
2638 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#returnKey */
2639 returnKey(returnKey: boolean): Cursor<T>;
2640 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#rewind */
2641 rewind(): void;
2642 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#setCursorOption */
2643 setCursorOption(field: string, value: object): Cursor<T>;
2644 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#setReadPreference */
2645 setReadPreference(readPreference: ReadPreferenceOrMode): Cursor<T>;
2646 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#showRecordId */
2647 showRecordId(showRecordId: boolean): Cursor<T>;
2648 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#skip */
2649 skip(value: number): Cursor<T>;
2650 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#snapshot */
2651 snapshot(snapshot: object): Cursor<T>;
2652 /** http://mongodb.github.io/node-mongodb-native/3.6/api/Cursor.html#sort */
2653 sort(keyOrList: string | Array<[string, number]> | SortOptionObject<T>, direction?: number): Cursor<T>;
2654 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#stream */
2655 stream(options?: { transform?: (document: T) => any }): Cursor<T>;
2656 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#toArray */
2657 toArray(): Promise<T[]>;
2658 toArray(callback: MongoCallback<T[]>): void;
2659 /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#unshift */
2660 unshift(stream: Buffer | string): void;
2661}
2662
2663/** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#count */
2664export interface CursorCommentOptions {
2665 skip?: number;
2666 limit?: number;
2667 maxTimeMS?: number;
2668 hint?: string;
2669 readPreference?: ReadPreferenceOrMode;
2670}
2671
2672/** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#~iteratorCallback */
2673export interface IteratorCallback<T> {
2674 (doc: T): void;
2675}
2676
2677/** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#~endCallback */
2678export interface EndCallback {
2679 (error: MongoError): void;
2680}
2681
2682/** http://mongodb.github.io/node-mongodb-native/3.1/api/AggregationCursor.html#~resultCallback */
2683export type AggregationCursorResult = object | null;
2684/** http://mongodb.github.io/node-mongodb-native/3.1/api/AggregationCursor.html */
2685export class AggregationCursor<T = Default> extends Cursor<T> {
2686 /** http://mongodb.github.io/node-mongodb-native/3.1/api/AggregationCursor.html#batchSize */
2687 batchSize(value: number): AggregationCursor<T>;
2688 /** http://mongodb.github.io/node-mongodb-native/3.1/api/AggregationCursor.html#clone */
2689 clone(): AggregationCursor<T>;
2690 /** http://mongodb.github.io/node-mongodb-native/3.1/api/AggregationCursor.html#close */
2691 close(): Promise<AggregationCursorResult>;
2692 close(callback: MongoCallback<AggregationCursorResult>): void;
2693 /** http://mongodb.github.io/node-mongodb-native/3.1/api/AggregationCursor.html#each */
2694 each(callback: MongoCallback<AggregationCursorResult>): void;
2695 /** http://mongodb.github.io/node-mongodb-native/3.1/api/AggregationCursor.html#explain */
2696 explain(): Promise<AggregationCursorResult>;
2697 explain(callback: MongoCallback<AggregationCursorResult>): void;
2698 /** http://mongodb.github.io/node-mongodb-native/3.1/api/AggregationCursor.html#geoNear */
2699 geoNear(document: object): AggregationCursor<T>;
2700 /** http://mongodb.github.io/node-mongodb-native/3.1/api/AggregationCursor.html#group */
2701 group<U = T>(document: object): AggregationCursor<U>;
2702 /** http://mongodb.github.io/node-mongodb-native/3.1/api/AggregationCursor.html#hasNext */
2703 hasNext(): Promise<boolean>;
2704 hasNext(callback: MongoCallback<boolean>): void;
2705 /** http://mongodb.github.io/node-mongodb-native/3.1/api/AggregationCursor.html#isClosed */
2706 isClosed(): boolean;
2707 /** http://mongodb.github.io/node-mongodb-native/3.1/api/AggregationCursor.html#limit */
2708 limit(value: number): AggregationCursor<T>;
2709 /** http://mongodb.github.io/node-mongodb-native/3.1/api/AggregationCursor.html#lookup */
2710 lookup(document: object): AggregationCursor<T>;
2711 /** http://mongodb.github.io/node-mongodb-native/3.1/api/AggregationCursor.html#match */
2712 match(document: object): AggregationCursor<T>;
2713 /** http://mongodb.github.io/node-mongodb-native/3.1/api/AggregationCursor.html#maxTimeMS */
2714 maxTimeMS(value: number): AggregationCursor<T>;
2715 /** http://mongodb.github.io/node-mongodb-native/3.1/api/AggregationCursor.html#next */
2716 next(): Promise<T | null>;
2717 next(callback: MongoCallback<T | null>): void;
2718 /** http://mongodb.github.io/node-mongodb-native/3.1/api/AggregationCursor.html#out */
2719 out(destination: string): AggregationCursor<T>;
2720 /** http://mongodb.github.io/node-mongodb-native/3.1/api/AggregationCursor.html#project */
2721 project<U = T>(document: object): AggregationCursor<U>;
2722 /** http://mongodb.github.io/node-mongodb-native/3.1/api/AggregationCursor.html#read */
2723 read(size: number): string | Buffer | void;
2724 /** http://mongodb.github.io/node-mongodb-native/3.1/api/AggregationCursor.html#redact */
2725 redact(document: object): AggregationCursor<T>;
2726 /** http://mongodb.github.io/node-mongodb-native/3.1/api/AggregationCursor.html#rewind */
2727 rewind(): AggregationCursor<T>;
2728 /** http://mongodb.github.io/node-mongodb-native/3.1/api/AggregationCursor.html#setEncoding */
2729 skip(value: number): AggregationCursor<T>;
2730 /** http://mongodb.github.io/node-mongodb-native/3.1/api/AggregationCursor.html#sort */
2731 sort(document: object): AggregationCursor<T>;
2732 /** http://mongodb.github.io/node-mongodb-native/3.1/api/AggregationCursor.html#toArray */
2733 toArray(): Promise<T[]>;
2734 toArray(callback: MongoCallback<T[]>): void;
2735 /** http://mongodb.github.io/node-mongodb-native/3.1/api/AggregationCursor.html#unshift */
2736 unshift(stream: Buffer | string): void;
2737 /** http://mongodb.github.io/node-mongodb-native/3.1/api/AggregationCursor.html#unwind */
2738 unwind<U = T>(
2739 field: string | { path: string; includeArrayIndex?: string; preserveNullAndEmptyArrays?: boolean },
2740 ): AggregationCursor<U>;
2741}
2742
2743/** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#~resultCallback */
2744export type CommandCursorResult = object | null;
2745/** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html */
2746export class CommandCursor extends Readable {
2747 /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#hasNext */
2748 hasNext(): Promise<boolean>;
2749 /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#hasNext */
2750 hasNext(callback: MongoCallback<boolean>): void;
2751 /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#batchSize */
2752 batchSize(value: number): CommandCursor;
2753 /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#clone */
2754 clone(): CommandCursor;
2755 /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#close */
2756 close(): Promise<CommandCursorResult>;
2757 close(callback: MongoCallback<CommandCursorResult>): void;
2758 /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#each */
2759 each(callback: MongoCallback<CommandCursorResult>): void;
2760 /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#isClosed */
2761 isClosed(): boolean;
2762 /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#maxTimeMS */
2763 maxTimeMS(value: number): CommandCursor;
2764 /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#next */
2765 next(): Promise<CommandCursorResult>;
2766 next(callback: MongoCallback<CommandCursorResult>): void;
2767 /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#read */
2768 read(size: number): string | Buffer | void;
2769 /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#rewind */
2770 rewind(): CommandCursor;
2771 /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#setReadPreference */
2772 setReadPreference(readPreference: ReadPreferenceOrMode): CommandCursor;
2773 /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#toArray */
2774 toArray(): Promise<any[]>;
2775 toArray(callback: MongoCallback<any[]>): void;
2776 /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#unshift */
2777 unshift(stream: Buffer | string): void;
2778}
2779
2780/** http://mongodb.github.io/node-mongodb-native/3.1/api/GridFSBucket.html */
2781export class GridFSBucket {
2782 constructor(db: Db, options?: GridFSBucketOptions);
2783 /** http://mongodb.github.io/node-mongodb-native/3.1/api/GridFSBucket.html#delete */
2784 delete(id: ObjectId, callback?: GridFSBucketErrorCallback): void;
2785 /** http://mongodb.github.io/node-mongodb-native/3.1/api/GridFSBucket.html#drop */
2786 drop(callback?: GridFSBucketErrorCallback): void;
2787 /** http://mongodb.github.io/node-mongodb-native/3.1/api/GridFSBucket.html#find */
2788 find(filter?: object, options?: GridFSBucketFindOptions): Cursor<any>;
2789 /** http://mongodb.github.io/node-mongodb-native/3.1/api/GridFSBucket.html#openDownloadStream */
2790 openDownloadStream(id: ObjectId, options?: { start: number; end: number }): GridFSBucketReadStream;
2791 /** http://mongodb.github.io/node-mongodb-native/3.1/api/GridFSBucket.html#openDownloadStreamByName */
2792 openDownloadStreamByName(
2793 filename: string,
2794 options?: { revision: number; start: number; end: number },
2795 ): GridFSBucketReadStream;
2796 /** http://mongodb.github.io/node-mongodb-native/3.1/api/GridFSBucket.html#openUploadStream */
2797 openUploadStream(filename: string, options?: GridFSBucketOpenUploadStreamOptions): GridFSBucketWriteStream;
2798 /** http://mongodb.github.io/node-mongodb-native/3.1/api/GridFSBucket.html#openUploadStreamWithId */
2799 openUploadStreamWithId(
2800 id: GridFSBucketWriteStreamId,
2801 filename: string,
2802 options?: GridFSBucketOpenUploadStreamOptions,
2803 ): GridFSBucketWriteStream;
2804 /** http://mongodb.github.io/node-mongodb-native/3.1/api/GridFSBucket.html#rename */
2805 rename(id: ObjectId, filename: string, callback?: GridFSBucketErrorCallback): void;
2806}
2807
2808/** http://mongodb.github.io/node-mongodb-native/3.1/api/GridFSBucket.html */
2809export interface GridFSBucketOptions {
2810 bucketName?: string;
2811 chunkSizeBytes?: number;
2812 writeConcern?: WriteConcern;
2813 readPreference?: ReadPreferenceOrMode;
2814}
2815
2816/** http://mongodb.github.io/node-mongodb-native/3.6/api/GridFSBucket.html#~errorCallback */
2817export interface GridFSBucketErrorCallback extends MongoCallback<void> {}
2818
2819/** http://mongodb.github.io/node-mongodb-native/3.1/api/GridFSBucket.html#find */
2820export interface GridFSBucketFindOptions {
2821 batchSize?: number;
2822 limit?: number;
2823 maxTimeMS?: number;
2824 noCursorTimeout?: boolean;
2825 skip?: number;
2826 sort?: object;
2827}
2828
2829/** https://mongodb.github.io/node-mongodb-native/3.1/api/GridFSBucket.html#openUploadStream */
2830export interface GridFSBucketOpenUploadStreamOptions {
2831 chunkSizeBytes?: number;
2832 metadata?: object;
2833 contentType?: string;
2834 aliases?: string[];
2835}
2836
2837/** https://mongodb.github.io/node-mongodb-native/3.1/api/GridFSBucketReadStream.html */
2838export class GridFSBucketReadStream extends Readable {
2839 id: ObjectId;
2840 constructor(
2841 chunks: Collection<any>,
2842 files: Collection<any>,
2843 readPreference: object,
2844 filter: object,
2845 options?: GridFSBucketReadStreamOptions,
2846 );
2847}
2848
2849/** https://mongodb.github.io/node-mongodb-native/3.1/api/GridFSBucketReadStream.html */
2850export interface GridFSBucketReadStreamOptions {
2851 sort?: number;
2852 skip?: number;
2853 start?: number;
2854 end?: number;
2855}
2856
2857/** https://mongodb.github.io/node-mongodb-native/3.1/api/GridFSBucketWriteStream.html */
2858export class GridFSBucketWriteStream extends Writable {
2859 id: GridFSBucketWriteStreamId;
2860 constructor(bucket: GridFSBucket, filename: string, options?: GridFSBucketWriteStreamOptions);
2861
2862 /**
2863 * Places this write stream into an aborted state (all future writes fail)
2864 * and deletes all chunks that have already been written.
2865 * @param [callback] called when chunks are successfully removed or error occurred
2866 * @see {@link https://mongodb.github.io/node-mongodb-native/3.6/api/GridFSBucketWriteStream.html#abort}
2867 */
2868 abort(callback?: GridFSBucketErrorCallback): void;
2869}
2870
2871/** https://mongodb.github.io/node-mongodb-native/3.1/api/GridFSBucketWriteStream.html */
2872export interface GridFSBucketWriteStreamOptions extends WriteConcern {
2873 /**
2874 * Custom file id for the GridFS file.
2875 */
2876 id?: GridFSBucketWriteStreamId;
2877 /**
2878 * The chunk size to use, in bytes
2879 */
2880 chunkSizeBytes?: number;
2881 /**
2882 * Default false; If true, disables adding an md5 field to file data
2883 */
2884 disableMD5?: boolean;
2885}
2886
2887/**
2888 * This is similar to Parameters but will work with a type which is
2889 * a function or with a tuple specifying arguments, which are both
2890 * common ways to define eventemitter events
2891 */
2892type EventArguments<T> = [T] extends [(...args: infer U) => any] ? U : [T] extends [undefined] ? [] : [T];
2893
2894/**
2895 * Type-safe event emitter from https://github.com/andywer/typed-emitter.
2896 *
2897 * Use it like this:
2898 *
2899 * interface MyEvents {
2900 * error: (error: Error) => void
2901 * message: (from: string, content: string) => void
2902 * }
2903 *
2904 * const myEmitter = new EventEmitter() as TypedEmitter<MyEvents>
2905 *
2906 * myEmitter.on("message", (from, content) => {
2907 * // ...
2908 * })
2909 *
2910 * myEmitter.emit("error", "x") // <- Will catch this type error
2911 */
2912declare class TypedEventEmitter<Events> {
2913 addListener<E extends keyof Events>(event: E, listener: Events[E]): this;
2914 on<E extends keyof Events>(event: E, listener: Events[E]): this;
2915 once<E extends keyof Events>(event: E, listener: Events[E]): this;
2916 prependListener<E extends keyof Events>(event: E, listener: Events[E]): this;
2917 prependOnceListener<E extends keyof Events>(event: E, listener: Events[E]): this;
2918
2919 off<E extends keyof Events>(event: E, listener: Events[E]): this;
2920 removeAllListeners<E extends keyof Events>(event?: E): this;
2921 removeListener<E extends keyof Events>(event: E, listener: Events[E]): this;
2922
2923 emit<E extends keyof Events>(event: E, ...args: EventArguments<Events[E]>): boolean;
2924 eventNames(): Array<keyof Events>;
2925 rawListeners<E extends keyof Events>(event: E): Function[];
2926 listeners<E extends keyof Events>(event: E): Function[];
2927 listenerCount<E extends keyof Events>(event: E): number;
2928
2929 getMaxListeners(): number;
2930 setMaxListeners(maxListeners: number): this;
2931}
2932
2933interface ChangeStreamEvents<TSchema extends { [key: string]: any } = DefaultSchema> {
2934 change: (doc: ChangeEvent<TSchema>) => void;
2935 close: () => void;
2936 end: () => void;
2937 error: (err: MongoError) => void;
2938 resumeTokenChanged: (newToken: ResumeToken) => void;
2939}
2940
2941/** http://mongodb.github.io/node-mongodb-native/3.3/api/ChangeStream.html */
2942export class ChangeStream<TSchema extends { [key: string]: any } = DefaultSchema> extends TypedEventEmitter<
2943 ChangeStreamEvents<TSchema>
2944> {
2945 resumeToken: ResumeToken;
2946
2947 constructor(parent: MongoClient | Db | Collection, pipeline: object[], options?: ChangeStreamOptions);
2948
2949 /** http://mongodb.github.io/node-mongodb-native/3.1/api/ChangeStream.html#close */
2950 close(): Promise<any>;
2951 close(callback: MongoCallback<any>): void;
2952
2953 /** http://mongodb.github.io/node-mongodb-native/3.1/api/ChangeStream.html#hasNext */
2954 hasNext(): Promise<any>;
2955 hasNext(callback: MongoCallback<any>): void;
2956
2957 /** http://mongodb.github.io/node-mongodb-native/3.1/api/ChangeStream.html#isClosed */
2958 isClosed(): boolean;
2959
2960 /** http://mongodb.github.io/node-mongodb-native/3.1/api/ChangeStream.html#next */
2961 next(): Promise<any>;
2962 next(callback: MongoCallback<any>): void;
2963
2964 /** http://mongodb.github.io/node-mongodb-native/3.1/api/ChangeStream.html#stream */
2965 stream(options?: { transform?: Function }): Cursor;
2966}
2967
2968export class ResumeToken {}
2969
2970export type ChangeEventTypes =
2971 | 'insert'
2972 | 'delete'
2973 | 'replace'
2974 | 'update'
2975 | 'drop'
2976 | 'rename'
2977 | 'dropDatabase'
2978 | 'invalidate';
2979export interface ChangeEventBase<TSchema extends { [key: string]: any } = DefaultSchema> {
2980 _id: ResumeToken;
2981 /**
2982 * We leave this off the base type so that we can differentiate
2983 * by checking its value and get intelligent types on the other fields
2984 */
2985 // operationType: ChangeEventTypes;
2986 ns: {
2987 db: string;
2988 coll: string;
2989 };
2990 clusterTime: Timestamp;
2991 txnNumber?: number;
2992 lsid?: {
2993 id: any;
2994 uid: any;
2995 };
2996}
2997export interface ChangeEventCR<TSchema extends { [key: string]: any } = DefaultSchema>
2998 extends ChangeEventBase<TSchema> {
2999 operationType: 'insert' | 'replace';
3000 fullDocument?: TSchema;
3001 documentKey: {
3002 _id: ExtractIdType<TSchema>;
3003 };
3004}
3005type FieldUpdates<TSchema> = Partial<TSchema> & { [key: string]: any };
3006export interface ChangeEventUpdate<TSchema extends { [key: string]: any } = DefaultSchema>
3007 extends ChangeEventBase<TSchema> {
3008 operationType: 'update';
3009 updateDescription: {
3010 /**
3011 * This is an object with all changed fields; if they are nested,
3012 * the keys will be paths, e.g. 'question.answer.0.text': 'new text'
3013 */
3014 updatedFields: FieldUpdates<TSchema>;
3015 removedFields: Array<keyof TSchema | string>;
3016 };
3017 fullDocument?: TSchema;
3018 documentKey: {
3019 _id: ExtractIdType<TSchema>;
3020 };
3021}
3022export interface ChangeEventDelete<TSchema extends { [key: string]: any } = DefaultSchema>
3023 extends ChangeEventBase<TSchema> {
3024 operationType: 'delete';
3025 documentKey: {
3026 _id: ExtractIdType<TSchema>;
3027 };
3028}
3029export interface ChangeEventRename<TSchema extends { [key: string]: any } = DefaultSchema>
3030 extends ChangeEventBase<TSchema> {
3031 operationType: 'rename';
3032 to: {
3033 db: string;
3034 coll: string;
3035 };
3036}
3037
3038export interface ChangeEventOther<TSchema extends { [key: string]: any } = DefaultSchema>
3039 extends ChangeEventBase<TSchema> {
3040 operationType: 'drop' | 'dropDatabase';
3041}
3042
3043export interface ChangeEventInvalidate<TSchema extends { [key: string]: any } = DefaultSchema> {
3044 _id: ResumeToken;
3045 operationType: 'invalidate';
3046 clusterTime: Timestamp;
3047}
3048
3049export type ChangeEvent<TSchema extends object = { _id: ObjectId }> =
3050 | ChangeEventCR<TSchema>
3051 | ChangeEventUpdate<TSchema>
3052 | ChangeEventDelete<TSchema>
3053 | ChangeEventRename<TSchema>
3054 | ChangeEventOther<TSchema>
3055 | ChangeEventInvalidate<TSchema>;
3056
3057/** https://mongodb.github.io/node-mongodb-native/3.3/api/global.html#ChangeStreamOptions */
3058export interface ChangeStreamOptions {
3059 fullDocument?: 'default' | 'updateLookup';
3060 maxAwaitTimeMS?: number;
3061 resumeAfter?: ResumeToken;
3062 startAfter?: ResumeToken;
3063 startAtOperationTime?: Timestamp;
3064 batchSize?: number;
3065 collation?: CollationDocument;
3066 readPreference?: ReadPreferenceOrMode;
3067}
3068
3069type GridFSBucketWriteStreamId = string | number | object | ObjectId;
3070
3071export interface LoggerOptions {
3072 /**
3073 * Custom logger function
3074 */
3075 loggerLevel?: string;
3076 /**
3077 * Override default global log level.
3078 */
3079 logger?: log;
3080}
3081
3082export type log = (message?: string, state?: LoggerState) => void;
3083
3084export interface LoggerState {
3085 type: string;
3086 message: string;
3087 className: string;
3088 pid: number;
3089 date: number;
3090}
3091
3092/** http://mongodb.github.io/node-mongodb-native/3.1/api/Logger.html */
3093export class Logger {
3094 constructor(className: string, options?: LoggerOptions);
3095 /**
3096 * Log a message at the debug level
3097 */
3098 debug(message: string, state: LoggerState): void;
3099 /**
3100 * Log a message at the warn level
3101 */
3102 warn(message: string, state: LoggerState): void;
3103 /**
3104 * Log a message at the info level
3105 */
3106 info(message: string, state: LoggerState): void;
3107 /**
3108 * Log a message at the error level
3109 */
3110 error(message: string, state: LoggerState): void;
3111 /**
3112 * Is the logger set at info level
3113 */
3114 isInfo(): boolean;
3115 /**
3116 * Is the logger set at error level
3117 */
3118 isError(): boolean;
3119 /**
3120 * Is the logger set at error level
3121 */
3122 isWarn(): boolean;
3123 /**
3124 * Is the logger set at debug level
3125 */
3126 isDebug(): boolean;
3127 /**
3128 * Resets the logger to default settings, error and no filtered classes
3129 */
3130 static reset(): void;
3131 /**
3132 * Get the current logger function
3133 */
3134 static currentLogger(): log;
3135 //Set the current logger function
3136 static setCurrentLogger(log: log): void;
3137 /**
3138 * Set what classes to log.
3139 */
3140 static filter(type: string, values: string[]): void;
3141 /**
3142 * Set the current log level
3143 */
3144 static setLevel(level: string): void;
3145}
3146
3147/** https://docs.mongodb.com/manual/reference/collation/#collation-document-fields */
3148export interface CollationDocument {
3149 locale: string;
3150 strength?: number;
3151 caseLevel?: boolean;
3152 caseFirst?: string;
3153 numericOrdering?: boolean;
3154 alternate?: string;
3155 maxVariable?: string;
3156 backwards?: boolean;
3157 normalization?: boolean;
3158}
3159
3160/** https://docs.mongodb.com/manual/reference/command/createIndexes/ */
3161export interface IndexSpecification {
3162 key: object;
3163 name?: string;
3164 background?: boolean;
3165 unique?: boolean;
3166 partialFilterExpression?: object;
3167 sparse?: boolean;
3168 expireAfterSeconds?: number;
3169 storageEngine?: object;
3170 weights?: object;
3171 default_language?: string;
3172 language_override?: string;
3173 textIndexVersion?: number;
3174 '2dsphereIndexVersion'?: number;
3175 bits?: number;
3176 min?: number;
3177 max?: number;
3178 bucketSize?: number;
3179 collation?: CollationDocument;
3180}