UNPKG

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