UNPKG

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