@types/mongodb
Version:
TypeScript definitions for MongoDB
1,261 lines (1,177 loc) • 125 kB
TypeScript
// Type definitions for MongoDB 3.5
// Project: https://github.com/mongodb/node-mongodb-native
// https://github.com/mongodb/node-mongodb-native/tree/3.1
// Definitions by: Federico Caselli <https://github.com/CaselIT>
// Alan Marcell <https://github.com/alanmarcell>
// Gaurav Lahoti <https://github.com/dante-101>
// Mariano Cortesi <https://github.com/mcortesi>
// Enrico Picci <https://github.com/EnricoPicci>
// Alexander Christie <https://github.com/AJCStriker>
// Julien Chaumond <https://github.com/julien-c>
// Dan Aprahamian <https://github.com/daprahamian>
// Denys Bushulyak <https://github.com/denys-bushulyak>
// Bastien Arata <https://github.com/BastienAr>
// Wan Bachtiar <https://github.com/sindbach>
// Geraldine Lemeur <https://github.com/geraldinelemeur>
// Dominik Heigl <https://github.com/various89>
// Angela-1 <https://github.com/angela-1>
// Hector Ribes <https://github.com/hector7>
// Florian Richter <https://github.com/floric>
// Erik Christensen <https://github.com/erikc5000>
// Nick Zahn <https://github.com/Manc>
// Jarom Loveridge <https://github.com/jloveridge>
// Luis Pais <https://github.com/ranguna>
// Hossein Saniei <https://github.com/HosseinAgha>
// Alberto Silva <https://github.com/albertossilva>
// Piotr Błażejewicz <https://github.com/peterblazejewicz>
// Linus Unnebäck <https://github.com/LinusU>
// Richard Bateman <https://github.com/taxilian>
// Igor Strebezhev <https://github.com/xamgore>
// Valentin Agachi <https://github.com/avaly>
// HitkoDev <https://github.com/HitkoDev>
// TJT <https://github.com/Celend>
// Julien TASSIN <https://github.com/jtassin>
// Anna Henningsen <https://github.com/addaleax>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// Minimum TypeScript Version: 3.2
// Documentation: https://mongodb.github.io/node-mongodb-native/3.1/api/
/// <reference types="node" />
/// <reference lib="esnext.asynciterable" />
import { Binary, Decimal128, Double, Int32, Long, ObjectId, Timestamp } from 'bson';
import { EventEmitter } from 'events';
import { Readable, Writable } from 'stream';
import { checkServerIdentity } from 'tls';
// We can use TypeScript Omit once minimum required TypeScript Version is above 3.5
type Omit<T, K> = Pick<T, Exclude<keyof T, K>>;
type FlattenIfArray<T> = T extends ReadonlyArray<infer R> ? R : T;
export function connect(uri: string, options?: MongoClientOptions): Promise<MongoClient>;
export function connect(uri: string, callback: MongoCallback<MongoClient>): void;
export function connect(uri: string, options: MongoClientOptions, callback: MongoCallback<MongoClient>): void;
export { Binary, DBRef, Decimal128, Double, Int32, Long, MaxKey, MinKey, ObjectID, ObjectId, Timestamp } from 'bson';
type NumericTypes = number | Decimal128 | Double | Int32 | Long;
// Class documentation : http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html
export class MongoClient extends EventEmitter {
constructor(uri: string, options?: MongoClientOptions);
/** http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html#.connect */
static connect(uri: string, callback: MongoCallback<MongoClient>): void;
static connect(uri: string, options?: MongoClientOptions): Promise<MongoClient>;
static connect(uri: string, options: MongoClientOptions, callback: MongoCallback<MongoClient>): void;
/** http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html#connect */
connect(): Promise<MongoClient>;
connect(callback: MongoCallback<MongoClient>): void;
/** http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html#close */
close(callback: MongoCallback<void>): void;
close(force?: boolean): Promise<void>;
close(force: boolean, callback: MongoCallback<void>): void;
/** http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html#db */
db(dbName?: string, options?: MongoClientCommonOption): Db;
/** http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html#isConnected */
isConnected(options?: MongoClientCommonOption): boolean;
/** http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html#logout */
logout(callback: MongoCallback<any>): void;
logout(options?: { dbName?: string }): Promise<any>;
logout(options: { dbName?: string }, callback: MongoCallback<any>): void;
/** http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html#startSession */
startSession(options?: SessionOptions): ClientSession;
/** http://mongodb.github.io/node-mongodb-native/3.3/api/MongoClient.html#watch */
watch<TSchema extends object = { _id: ObjectId }>(
pipeline?: object[],
options?: ChangeStreamOptions & { session?: ClientSession },
): ChangeStream<TSchema>;
/** http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html#withSession */
withSession(operation: (session: ClientSession) => Promise<any>): Promise<void>;
/** http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html#withSession */
withSession(options: SessionOptions, operation: (session: ClientSession) => Promise<any>): Promise<void>;
readPreference: ReadPreference;
writeConcern: WriteConcern;
}
/**
* http://mongodb.github.io/node-mongodb-native/3.1/api/ClientSession.html
*/
export interface ClientSession extends EventEmitter {
/** The server id associated with this session */
id: any;
/**
* Aborts the currently active transaction in this session.
* @param cb Optional callback for completion of this operation
*/
abortTransaction(cb?: MongoCallback<void>): Promise<void>;
/**
* Advances the operationTime for a ClientSession.
*/
advanceOperationTime(operamtionTime: Timestamp): void;
/**
* Commits the currently active transaction in this session.
* @param cb Optional callback for completion of this operation
*/
commitTransaction(cb?: MongoCallback<void>): Promise<void>;
/**
* Ends this session on the server
* @param cb Optional callback for completion of this operation
*/
endSession(cb?: MongoCallback<void>): void;
/**
* Ends this session on the server
* @param options Optional settings. Currently reserved for future use
* @param cb Optional callback for completion of this operation
*/
endSession(options: any, cb?: MongoCallback<void>): void;
/**
* Used to determine if this session equals another
*
* @param session A class representing a client session on the server
* @returns Whether the sessions are equal
*/
equals(session: ClientSession): boolean;
/** Increment the transaction number on the internal ServerSession */
incrementTransactionNumber(): void;
/**
* @returns Whether this session is currently in a transaction or not
*/
inTransaction(): boolean;
/**
* Starts a new transaction with the given options.
*/
startTransaction(options?: TransactionOptions): void;
/**
* Runs a provided lambda within a transaction, retrying either the commit operation
* or entire transaction as needed (and when the error permits) to better ensure that
* the transaction can complete successfully.
*
* IMPORTANT: This method requires the user to return a Promise, all lambdas that do not
* return a Promise will result in undefined behavior.
*
* @param fn Function to execute with the new session.
* @param options Optional settings for the transaction
*/
withTransaction<T>(fn: WithTransactionCallback<T>, options?: TransactionOptions): Promise<void>;
}
// http://mongodb.github.io/node-mongodb-native/3.1/api/global.html#ReadConcern
type ReadConcernLevel = 'local' | 'available' | 'majority' | 'linearizable' | 'snapshot';
/**
* The MongoDB ReadConcern, which allows for control of the consistency and isolation properties
* of the data read from replica sets and replica set shards.
* http://mongodb.github.io/node-mongodb-native/3.1/api/global.html#ReadConcern
*/
export interface ReadConcern {
level: ReadConcernLevel;
}
/**
* A MongoDB WriteConcern, which describes the level of acknowledgement
* requested from MongoDB for write operations.
* http://mongodb.github.io/node-mongodb-native/3.1/api/global.html#WriteConcern
*/
interface WriteConcern {
/**
* requests acknowledgement that the write operation has
* propagated to a specified number of mongod hosts
* @default 1
*/
w?: number | 'majority' | string;
/**
* requests acknowledgement from MongoDB that the write operation has
* been written to the journal
* @default false
*/
j?: boolean;
/**
* a time limit, in milliseconds, for the write concern
*/
wtimeout?: number;
}
/**
* Options to pass when creating a Client Session
* http://mongodb.github.io/node-mongodb-native/3.1/api/global.html#SessionOptions
*/
export interface SessionOptions {
/**
* Whether causal consistency should be enabled on this session
* @default true
*/
causalConsistency?: boolean;
/**
* The default TransactionOptions to use for transactions started on this session.
*/
defaultTransactionOptions?: TransactionOptions;
}
/**
* Configuration options for a transaction.
* http://mongodb.github.io/node-mongodb-native/3.1/api/global.html#TransactionOptions
*/
export interface TransactionOptions {
readConcern?: ReadConcern;
writeConcern?: WriteConcern;
readPreference?: ReadPreferenceOrMode;
}
export interface MongoClientCommonOption {
/** Do not make the db an event listener to the original connection. */
noListener?: boolean;
/** Control if you want to return a cached instance or have a new one created */
returnNonCachedInstance?: boolean;
}
export interface MongoCallback<T> {
(error: MongoError, result: T): void;
}
export type WithTransactionCallback<T> = (session: ClientSession) => Promise<T>;
/**
* Creates a new MongoError
* see {@link http://mongodb.github.io/node-mongodb-native/3.5/api/MongoError.html}
*/
export class MongoError extends Error {
constructor(message: string | Error | object);
/**
* @deprecated
*/
static create(options: string | Error | object): MongoError;
/**
* Checks the error to see if it has an error label
*/
hasErrorLabel(label: string): boolean;
code?: number | string;
/**
* While not documented, the 'errmsg' prop is AFAIK the only way to find out
* which unique index caused a duplicate key error. When you have multiple
* unique indexes on a collection, knowing which index caused a duplicate
* key error enables you to send better (more precise) error messages to the
* client/user (eg. "Email address must be unique" instead of "Both email
* address and username must be unique") - which caters for a better (app)
* user experience.
*
* Details: https://github.com/Automattic/mongoose/issues/2129 (issue for
* mongoose, but the same applies for the native mongodb driver)
*
* Note that in mongoose (the link above) the prop in question is called
* 'message' while in mongodb it is called 'errmsg'. This can be seen in
* multiple places in the source code, for example here:
* https://github.com/mongodb/node-mongodb-native/blob/a12aa15ac3eaae3ad5c4166ea1423aec4560f155/test/functional/find_tests.js#L1111
*/
errmsg?: string;
name: string;
}
/**
* An error indicating an issue with the network, including TCP errors and timeouts
* see {@link https://mongodb.github.io/node-mongodb-native/3.5/api/MongoNetworkError.html}
*/
export class MongoNetworkError extends MongoError {
constructor(message: string);
errorLabels: string[];
}
/**
* An error used when attempting to parse a value (like a connection string)
* see {@link https://mongodb.github.io/node-mongodb-native/3.5/api/MongoParseError.html}
*/
export class MongoParseError extends MongoError {
constructor(message: string);
}
/** http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html#.connect */
export interface MongoClientOptions
extends DbCreateOptions,
ServerOptions,
MongosOptions,
ReplSetOptions,
SocketOptions,
SSLOptions,
TLSOptions,
HighAvailabilityOptions,
WriteConcern,
UnifiedTopologyOptions {
/**
* The logging level (error/warn/info/debug)
*/
loggerLevel?: string;
/**
* Custom logger object
*/
logger?: object | log;
/**
* Validate MongoClient passed in options for correctness.
* Default: false
*/
validateOptions?: object | boolean;
/**
* The name of the application that created this MongoClient instance.
*/
appname?: string;
/**
* Authentication credentials
*/
auth?: {
/**
* The username for auth
*/
user: string;
/**
* The password for auth
*/
password: string;
};
/**
* Determines whether or not to use the new url parser. Enables the new, spec-compliant
* url parser shipped in the core driver. This url parser fixes a number of problems with
* the original parser, and aims to outright replace that parser in the near future.
*/
useNewUrlParser?: boolean;
/**
* number of retries for a tailable cursor
* @default 5
*/
numberOfRetries?: number;
/**
* Mechanism for authentication: DEFAULT, GSSAPI, PLAIN, MONGODB-X509, 'MONGODB-CR', SCRAM-SHA-1 or SCRAM-SHA-256
*/
authMechanism?:
| 'DEFAULT'
| 'GSSAPI'
| 'PLAIN'
| 'MONGODB-X509'
| 'MONGODB-CR'
| 'SCRAM-SHA-1'
| 'SCRAM-SHA-256'
| string;
/** Type of compression to use */
compression?: {
/** The selected compressors in preference order */
compressors?: Array<'snappy' | 'zlib'>;
};
}
export interface SSLOptions {
/**
* 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.
*/
ciphers?: string;
/**
* 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.
*/
ecdhCurve?: string;
/**
* Default:5; Number of connections for each server instance; set to 5 as default for legacy reasons.
*/
poolSize?: number;
/**
* If present, the connection pool will be initialized with minSize connections, and will never dip below minSize connections
*/
minSize?: number;
/**
* Use ssl connection (needs to have a mongod server with ssl support)
*/
ssl?: boolean;
/**
* Default: true; Validate mongod server certificate against ca (mongod server >=2.4 with ssl support required)
*/
sslValidate?: boolean;
/**
* Default: true; Server identity checking during SSL
*/
checkServerIdentity?: boolean | typeof checkServerIdentity;
/**
* Array of valid certificates either as Buffers or Strings
*/
sslCA?: ReadonlyArray<Buffer | string>;
/**
* SSL Certificate revocation list binary buffer
*/
sslCRL?: ReadonlyArray<Buffer | string>;
/**
* SSL Certificate binary buffer
*/
sslCert?: Buffer | string;
/**
* SSL Key file binary buffer
*/
sslKey?: Buffer | string;
/**
* SSL Certificate pass phrase
*/
sslPass?: Buffer | string;
/**
* String containing the server name requested via TLS SNI.
*/
servername?: string;
}
export interface TLSOptions {
/**
* Enable TLS connections
* @default false
*/
tls?: boolean;
/**
* Relax TLS constraints, disabling validation
* @default false
*/
tlsInsecure?: boolean;
/**
* path to file with either a single or bundle of certificate authorities
* to be considered trusted when making a TLS connection
*/
tlsCAFile?: string;
/**
* path to the client certificate file or the client private key file;
* in the case that they both are needed, the files should be concatenated
*/
tlsCertificateKeyFile?: string;
/**
* The password to decrypt the client private key to be used for TLS connections
*/
tlsCertificateKeyFilePassword?: string;
/**
* Specifies whether or not the driver should error when the server’s TLS certificate is invalid
*/
tlsAllowInvalidCertificates?: boolean;
/**
* Specifies whether or not the driver should error when there is a mismatch between the server’s hostname
* and the hostname specified by the TLS certificate
*/
tlsAllowInvalidHostnames?: boolean;
}
export interface HighAvailabilityOptions {
/**
* Default: true; Turn on high availability monitoring.
*/
ha?: boolean;
/**
* Default: 10000; The High availability period for replicaset inquiry
*/
haInterval?: number;
/**
* Default: false;
*/
domainsEnabled?: boolean;
/** The ReadPreference mode as listed here: http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html */
readPreference?: ReadPreferenceOrMode;
/** An object representing read preference tags, see: http://mongodb.github.io/node-mongodb-native/3.1/api/ReadPreference.html */
readPreferenceTags?: string[];
}
export type ReadPreferenceMode = 'primary' | 'primaryPreferred' | 'secondary' | 'secondaryPreferred' | 'nearest';
export type ReadPreferenceOrMode = ReadPreference | ReadPreferenceMode;
export type ReadPreferenceOptions = {
hedge?: { enabled?: boolean };
/**
* Max Secondary Read Staleness in Seconds
*/
maxStalenessSeconds?: number;
};
// See http://mongodb.github.io/node-mongodb-native/3.1/api/ReadPreference.html
export class ReadPreference {
constructor(mode: ReadPreferenceMode, tags: object, options?: ReadPreferenceOptions);
mode: ReadPreferenceMode;
tags: any;
static PRIMARY: 'primary';
static PRIMARY_PREFERRED: 'primaryPreferred';
static SECONDARY: 'secondary';
static SECONDARY_PREFERRED: 'secondaryPreferred';
static NEAREST: 'nearest';
isValid(mode: string): boolean;
static isValid(mode: string): boolean;
}
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html */
export interface DbCreateOptions extends CommonOptions {
/**
* If the database authentication is dependent on another databaseName.
*/
authSource?: string;
/**
* Default: false; Force server to create _id fields instead of client.
*/
forceServerObjectId?: boolean;
/**
* Default: false; Use c++ bson parser.
*/
native_parser?: boolean;
/**
* Serialize functions on any object.
*/
serializeFunctions?: boolean;
/**
* Specify if the BSON serializer should ignore undefined fields.
*/
ignoreUndefined?: boolean;
/**
* Return document results as raw BSON buffers.
*/
raw?: boolean;
/**
* Default: true; Promotes Long values to number if they fit inside the 53 bits resolution.
*/
promoteLongs?: boolean;
/**
* Default: false; Promotes Binary BSON values to native Node Buffers
*/
promoteBuffers?: boolean;
/**
* the prefered read preference. use 'ReadPreference' class.
*/
readPreference?: ReadPreferenceOrMode;
/**
* Default: true; Promotes BSON values to native types where possible, set to false to only receive wrapper types.
*/
promoteValues?: boolean;
/**
* Custom primary key factory to generate _id values (see Custom primary keys).
*/
pkFactory?: object;
/**
* ES6 compatible promise constructor
*/
promiseLibrary?: PromiseConstructor;
/**
* https://docs.mongodb.com/manual/reference/read-concern/#read-concern
*/
readConcern?: ReadConcern | string;
/**
* Sets a cap on how many operations the driver will buffer up before giving up on getting a
* working connection, default is -1 which is unlimited.
*/
bufferMaxEntries?: number;
}
export interface UnifiedTopologyOptions {
/**
* Enables the new unified topology layer
*/
useUnifiedTopology?: boolean;
/**
* **Only applies to the unified topology**
* The size of the latency window for selecting among multiple suitable servers
* @default 15
*/
localThresholdMS?: number;
/**
* With `useUnifiedTopology`, the MongoDB driver will try to find a server to send any given operation to
* and keep retrying for `serverSelectionTimeoutMS` milliseconds.
* Default: 30000
*/
serverSelectionTimeoutMS?: number;
/**
* **Only applies to the unified topology**
* The frequency with which topology updates are scheduled
* @default 10000
*/
heartbeatFrequencyMS?: number;
/**
* **Only applies to the unified topology**
* The maximum number of connections that may be associated with a pool at a given time.
* This includes in use and available connections
* @default 10
*/
maxPoolSize?: number;
/**
* **Only applies to the unified topology**
* The minimum number of connections that MUST exist at any moment in a single connection pool.
* @default 0
*/
minPoolSize?: number;
/**
* **Only applies to the unified topology**
* The maximum amount of time a connection should remain idle in the connection pool before being marked idle.
* @default Infinity
*/
maxIdleTimeMS?: number;
/**
* **Only applies to the unified topology**
* The maximum amount of time operation execution should wait for a connection to become available.
* The default is 0 which means there is no limit.
* @default 0
*/
waitQueueTimeoutMS?: number;
}
/** http://mongodb.github.io/node-mongodb-native/3.6/api/Server.html */
export interface SocketOptions {
/**
* Reconnect on error.
* @default true
*/
autoReconnect?: boolean;
/**
* TCP Socket NoDelay option.
* @default true
*/
noDelay?: boolean;
/**
* TCP KeepAlive enabled on the socket.
* @default true
*/
keepAlive?: boolean;
/**
* TCP KeepAlive initial delay before sending first keep-alive packet when idle.
* @default 30000
*/
keepAliveInitialDelay?: number;
/**
* TCP Connection timeout setting.
* @default 10000
*/
connectTimeoutMS?: number;
/**
* Version of IP stack. Can be 4, 6 or null.
* @default null
*
* If null, will attempt to connect with IPv6, and will fall back to IPv4 on failure
* refer to http://mongodb.github.io/node-mongodb-native/3.6/api/MongoClient.html
*/
family?: 4 | 6 | null;
/**
* TCP Socket timeout setting.
* @default 360000
*/
socketTimeoutMS?: number;
}
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Server.html */
export interface ServerOptions extends SSLOptions {
/**
* If you're connected to a single server or mongos proxy (as opposed to a replica set),
* the MongoDB driver will try to reconnect every reconnectInterval milliseconds for reconnectTries
* times, and give up afterward. When the driver gives up, the mongoose connection emits a
* reconnectFailed event.
* @default 30
*/
reconnectTries?: number;
/**
* Will wait # milliseconds between retries
* @default 1000
*/
reconnectInterval?: number;
/**
* @default true
*/
monitoring?: boolean;
/**
* Enable command monitoring for this client
* @default false
*/
monitorCommands?: boolean;
/**
* Socket Options
*/
socketOptions?: SocketOptions;
/**
* The High availability period for replicaset inquiry
* @default 10000
*/
haInterval?: number;
/**
* @default false
*/
domainsEnabled?: boolean;
/**
* Specify a file sync write concern
* @default false
*/
fsync?: boolean;
}
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Mongos.html */
export interface MongosOptions extends SSLOptions, HighAvailabilityOptions {
/**
* Default: 15; Cutoff latency point in MS for MongoS proxy selection
*/
acceptableLatencyMS?: number;
/**
* Socket Options
*/
socketOptions?: SocketOptions;
}
/** http://mongodb.github.io/node-mongodb-native/3.1/api/ReplSet.html */
export interface ReplSetOptions extends SSLOptions, HighAvailabilityOptions {
/**
* The max staleness to secondary reads (values under 10 seconds cannot be guaranteed);
*/
maxStalenessSeconds?: number;
/**
* The name of the replicaset to connect to.
*/
replicaSet?: string;
/**
* Default: 15 ; Range of servers to pick when using NEAREST (lowest ping ms + the latency fence, ex: range of 1 to (1 + 15) ms)
*/
secondaryAcceptableLatencyMS?: number;
connectWithNoPrimary?: boolean;
socketOptions?: SocketOptions;
}
export type ProfilingLevel = 'off' | 'slow_only' | 'all';
// Class documentation : http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html
export class Db extends EventEmitter {
constructor(databaseName: string, serverConfig: Server | ReplSet | Mongos, options?: DbCreateOptions);
serverConfig: Server | ReplSet | Mongos;
bufferMaxEntries: number;
databaseName: string;
options: any;
native_parser: boolean;
slaveOk: boolean;
writeConcern: WriteConcern;
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#addUser */
addUser(username: string, password: string, callback: MongoCallback<any>): void;
addUser(username: string, password: string, options?: DbAddUserOptions): Promise<any>;
addUser(username: string, password: string, options: DbAddUserOptions, callback: MongoCallback<any>): void;
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#admin */
admin(): Admin;
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#collection */
collection<TSchema = DefaultSchema>(
name: string,
callback?: MongoCallback<Collection<TSchema>>,
): Collection<TSchema>;
collection<TSchema = DefaultSchema>(
name: string,
options: DbCollectionOptions,
callback?: MongoCallback<Collection<TSchema>>,
): Collection<TSchema>;
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#collections */
collections(): Promise<Array<Collection<Default>>>;
collections(callback: MongoCallback<Array<Collection<Default>>>): void;
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#command */
command(command: object, callback: MongoCallback<any>): void;
command(command: object, options?: { readPreference?: ReadPreferenceOrMode; session?: ClientSession }): Promise<any>;
command(
command: object,
options: { readPreference: ReadPreferenceOrMode; session?: ClientSession },
callback: MongoCallback<any>,
): void;
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#createCollection */
createCollection<TSchema = DefaultSchema>(name: string, callback: MongoCallback<Collection<TSchema>>): void;
createCollection<TSchema = DefaultSchema>(
name: string,
options?: CollectionCreateOptions,
): Promise<Collection<TSchema>>;
createCollection<TSchema = DefaultSchema>(
name: string,
options: CollectionCreateOptions,
callback: MongoCallback<Collection<TSchema>>,
): void;
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#createIndex */
createIndex(name: string, fieldOrSpec: string | object, callback: MongoCallback<any>): void;
createIndex(name: string, fieldOrSpec: string | object, options?: IndexOptions): Promise<any>;
createIndex(name: string, fieldOrSpec: string | object, options: IndexOptions, callback: MongoCallback<any>): void;
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#dropCollection */
dropCollection(name: string): Promise<boolean>;
dropCollection(name: string, callback: MongoCallback<boolean>): void;
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#dropDatabase */
dropDatabase(): Promise<any>;
dropDatabase(callback: MongoCallback<any>): void;
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#executeDbAdminCommand */
executeDbAdminCommand(command: object, callback: MongoCallback<any>): void;
executeDbAdminCommand(
command: object,
options?: { readPreference?: ReadPreferenceOrMode; session?: ClientSession },
): Promise<any>;
executeDbAdminCommand(
command: object,
options: { readPreference?: ReadPreferenceOrMode; session?: ClientSession },
callback: MongoCallback<any>,
): void;
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#indexInformation */
indexInformation(name: string, callback: MongoCallback<any>): void;
indexInformation(name: string, options?: { full?: boolean; readPreference?: ReadPreferenceOrMode }): Promise<any>;
indexInformation(
name: string,
options: { full?: boolean; readPreference?: ReadPreferenceOrMode },
callback: MongoCallback<any>,
): void;
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#listCollections */
listCollections(
filter?: object,
options?: {
nameOnly?: boolean;
batchSize?: number;
readPreference?: ReadPreferenceOrMode;
session?: ClientSession;
},
): CommandCursor;
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#profilingInfo */
/** @deprecated Query the system.profile collection directly. */
profilingInfo(callback: MongoCallback<any>): void;
profilingInfo(options?: { session?: ClientSession }): Promise<void>;
profilingInfo(options: { session?: ClientSession }, callback: MongoCallback<void>): void;
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#profilingLevel */
profilingLevel(callback: MongoCallback<ProfilingLevel>): void;
profilingLevel(options?: { session?: ClientSession }): Promise<ProfilingLevel>;
profilingLevel(options: { session?: ClientSession }, callback: MongoCallback<ProfilingLevel>): void;
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#removeUser */
removeUser(username: string, callback: MongoCallback<any>): void;
removeUser(username: string, options?: CommonOptions): Promise<any>;
removeUser(username: string, options: CommonOptions, callback: MongoCallback<any>): void;
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#renameCollection */
renameCollection<TSchema = DefaultSchema>(
fromCollection: string,
toCollection: string,
callback: MongoCallback<Collection<TSchema>>,
): void;
renameCollection<TSchema = DefaultSchema>(
fromCollection: string,
toCollection: string,
options?: { dropTarget?: boolean },
): Promise<Collection<TSchema>>;
renameCollection<TSchema = DefaultSchema>(
fromCollection: string,
toCollection: string,
options: { dropTarget?: boolean },
callback: MongoCallback<Collection<TSchema>>,
): void;
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#setProfilingLevel */
setProfilingLevel(level: ProfilingLevel, callback: MongoCallback<ProfilingLevel>): void;
setProfilingLevel(level: ProfilingLevel, options?: { session?: ClientSession }): Promise<ProfilingLevel>;
setProfilingLevel(
level: ProfilingLevel,
options: { session?: ClientSession },
callback: MongoCallback<ProfilingLevel>,
): void;
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#stats */
stats(callback: MongoCallback<any>): void;
stats(options?: { scale?: number }): Promise<any>;
stats(options: { scale?: number }, callback: MongoCallback<any>): void;
/** http://mongodb.github.io/node-mongodb-native/3.3/api/Db.html#watch */
watch<TSchema extends object = { _id: ObjectId }>(
pipeline?: object[],
options?: ChangeStreamOptions & { session?: ClientSession },
): ChangeStream<TSchema>;
}
export interface CommonOptions extends WriteConcern {
session?: ClientSession;
}
/**
* @deprecated
* @see http://mongodb.github.io/node-mongodb-native/3.1/api/Server.html
*/
export class Server extends EventEmitter {
constructor(host: string, port: number, options?: ServerOptions);
connections(): any[];
}
/**
* @deprecated
* @see http://mongodb.github.io/node-mongodb-native/3.1/api/ReplSet.html
*/
export class ReplSet extends EventEmitter {
constructor(servers: Server[], options?: ReplSetOptions);
connections(): any[];
}
/**
* @deprecated
* @see http://mongodb.github.io/node-mongodb-native/3.1/api/Mongos.html
*/
export class Mongos extends EventEmitter {
constructor(servers: Server[], options?: MongosOptions);
connections(): any[];
}
/**
* @deprecated
* @see http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#addUser
*/
export interface DbAddUserOptions extends CommonOptions {
customData?: object;
roles?: object[];
}
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#createCollection */
export interface CollectionCreateOptions extends CommonOptions {
raw?: boolean;
pkFactory?: object;
readPreference?: ReadPreferenceOrMode;
serializeFunctions?: boolean;
strict?: boolean;
capped?: boolean;
autoIndexId?: boolean;
size?: number;
max?: number;
flags?: number;
storageEngine?: object;
validator?: object;
validationLevel?: 'off' | 'strict' | 'moderate';
validationAction?: 'error' | 'warn';
indexOptionDefaults?: object;
viewOn?: string;
pipeline?: any[];
collation?: CollationDocument;
}
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#collection */
export interface DbCollectionOptions extends CommonOptions {
raw?: boolean;
pkFactory?: object;
readPreference?: ReadPreferenceOrMode;
serializeFunctions?: boolean;
strict?: boolean;
readConcern?: ReadConcern;
}
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#createIndex */
export interface IndexOptions extends CommonOptions {
/**
* Creates an unique index.
*/
unique?: boolean;
/**
* Creates a sparse index.
*/
sparse?: boolean;
/**
* Creates the index in the background, yielding whenever possible.
*/
background?: boolean;
/**
* A unique index cannot be created on a key that has pre-existing duplicate values.
*
* If you would like to create the index anyway, keeping the first document the database indexes and
* deleting all subsequent documents that have duplicate value
*/
dropDups?: boolean;
/**
* For geo spatial indexes set the lower bound for the co-ordinates.
*/
min?: number;
/**
* For geo spatial indexes set the high bound for the co-ordinates.
*/
max?: number;
/**
* Specify the format version of the indexes.
*/
v?: number;
/**
* Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher)
*/
expireAfterSeconds?: number;
/**
* Override the auto generated index name (useful if the resulting name is larger than 128 bytes)
*/
name?: string;
/**
* Creates a partial index based on the given filter object (MongoDB 3.2 or higher)
*/
partialFilterExpression?: any;
collation?: CollationDocument;
default_language?: string;
}
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Admin.html */
export interface Admin {
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Admin.html#addUser */
addUser(username: string, password: string, callback: MongoCallback<any>): void;
addUser(username: string, password: string, options?: AddUserOptions): Promise<any>;
addUser(username: string, password: string, options: AddUserOptions, callback: MongoCallback<any>): void;
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Admin.html#buildInfo */
buildInfo(options?: { session?: ClientSession }): Promise<any>;
buildInfo(options: { session?: ClientSession }, callback: MongoCallback<any>): void;
buildInfo(callback: MongoCallback<any>): void;
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Admin.html#command */
command(command: object, callback: MongoCallback<any>): void;
command(command: object, options?: { readPreference?: ReadPreferenceOrMode; maxTimeMS?: number }): Promise<any>;
command(
command: object,
options: { readPreference?: ReadPreferenceOrMode; maxTimeMS?: number },
callback: MongoCallback<any>,
): void;
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Admin.html#listDatabases */
listDatabases(options?: { nameOnly?: boolean; session?: ClientSession }): Promise<any>;
listDatabases(options: { nameOnly?: boolean; session?: ClientSession }, callback: MongoCallback<any>): void;
listDatabases(callback: MongoCallback<any>): void;
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Admin.html#ping */
ping(options?: { session?: ClientSession }): Promise<any>;
ping(options: { session?: ClientSession }, callback: MongoCallback<any>): void;
ping(callback: MongoCallback<any>): void;
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Admin.html#removeUser */
removeUser(username: string, callback: MongoCallback<any>): void;
removeUser(username: string, options?: FSyncOptions): Promise<any>;
removeUser(username: string, options: FSyncOptions, callback: MongoCallback<any>): void;
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Admin.html#replSetGetStatus */
replSetGetStatus(options?: { session?: ClientSession }): Promise<any>;
replSetGetStatus(options: { session?: ClientSession }, callback: MongoCallback<any>): void;
replSetGetStatus(callback: MongoCallback<any>): void;
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Admin.html#serverInfo */
serverInfo(): Promise<any>;
serverInfo(callback: MongoCallback<any>): void;
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Admin.html#serverStatus */
serverStatus(options?: { session?: ClientSession }): Promise<any>;
serverStatus(options: { session?: ClientSession }, callback: MongoCallback<any>): void;
serverStatus(callback: MongoCallback<any>): void;
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Admin.html#validateCollection */
validateCollection(collectionNme: string, callback: MongoCallback<any>): void;
validateCollection(collectionNme: string, options?: object): Promise<any>;
validateCollection(collectionNme: string, options: object, callback: MongoCallback<any>): void;
}
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Admin.html#addUser */
export interface AddUserOptions extends CommonOptions {
fsync: boolean;
customData?: object;
roles?: object[];
}
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Admin.html#removeUser */
export interface FSyncOptions extends CommonOptions {
fsync?: boolean;
}
// TypeScript Omit (Exclude to be specific) does not work for objects with an "any" indexed type
type EnhancedOmit<T, K> = string | number extends keyof T
? T // T has indexed type e.g. { _id: string; [k: string]: any; } or it is "any"
: Omit<T, K>;
type ExtractIdType<TSchema> = TSchema extends { _id: infer U } // user has defined a type for _id
? {} extends U
? Exclude<U, {}>
: unknown extends U
? ObjectId
: U
: ObjectId; // user has not defined _id on schema
// this makes _id optional
export type OptionalId<TSchema extends { _id?: any }> = ObjectId extends TSchema['_id']
? // a Schema with ObjectId _id type or "any" or "indexed type" provided
EnhancedOmit<TSchema, '_id'> & { _id?: ExtractIdType<TSchema> }
: // a Schema provided but _id type is not ObjectId
WithId<TSchema>;
// this adds _id as a required property
export type WithId<TSchema> = EnhancedOmit<TSchema, '_id'> & { _id: ExtractIdType<TSchema> };
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html */
export interface Collection<TSchema extends { [key: string]: any } = DefaultSchema> {
/**
* Get the collection name.
*/
collectionName: string;
/**
* Get the full collection namespace.
*/
namespace: string;
/**
* The current write concern values.
*/
writeConcern: WriteConcern;
/**
* The current read concern values.
*/
readConcern: ReadConcern;
/**
* Get current index hint for collection.
*/
hint: any;
/** http://mongodb.github.io/node-mongodb-native/3.0/api/Collection.html#aggregate */
aggregate<T = TSchema>(callback: MongoCallback<AggregationCursor<T>>): AggregationCursor<T>;
aggregate<T = TSchema>(pipeline: object[], callback: MongoCallback<AggregationCursor<T>>): AggregationCursor<T>;
aggregate<T = TSchema>(
pipeline?: object[],
options?: CollectionAggregationOptions,
callback?: MongoCallback<AggregationCursor<T>>,
): AggregationCursor<T>;
/** http://mongodb.github.io/node-mongodb-native/3.0/api/Collection.html#bulkWrite */
bulkWrite(operations: Array<BulkWriteOperation<TSchema>>, callback: MongoCallback<BulkWriteOpResultObject>): void;
bulkWrite(
operations: Array<BulkWriteOperation<TSchema>>,
options?: CollectionBulkWriteOptions,
): Promise<BulkWriteOpResultObject>;
bulkWrite(
operations: Array<BulkWriteOperation<TSchema>>,
options: CollectionBulkWriteOptions,
callback: MongoCallback<BulkWriteOpResultObject>,
): void;
/**
* http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#count
* @deprecated Use countDocuments or estimatedDocumentCount
*/
count(callback: MongoCallback<number>): void;
count(query: FilterQuery<TSchema>, callback: MongoCallback<number>): void;
count(query?: FilterQuery<TSchema>, options?: MongoCountPreferences): Promise<number>;
count(query: FilterQuery<TSchema>, options: MongoCountPreferences, callback: MongoCallback<number>): void;
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#countDocuments */
countDocuments(callback: MongoCallback<number>): void;
countDocuments(query: FilterQuery<TSchema>, callback: MongoCallback<number>): void;
countDocuments(query?: FilterQuery<TSchema>, options?: MongoCountPreferences): Promise<number>;
countDocuments(query: FilterQuery<TSchema>, options: MongoCountPreferences, callback: MongoCallback<number>): void;
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#createIndex */
createIndex(fieldOrSpec: string | any, callback: MongoCallback<string>): void;
createIndex(fieldOrSpec: string | any, options?: IndexOptions): Promise<string>;
createIndex(fieldOrSpec: string | any, options: IndexOptions, callback: MongoCallback<string>): void;
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#createIndexes and http://docs.mongodb.org/manual/reference/command/createIndexes/ */
createIndexes(indexSpecs: IndexSpecification[], callback: MongoCallback<any>): void;
createIndexes(indexSpecs: IndexSpecification[], options?: { session?: ClientSession }): Promise<any>;
createIndexes(
indexSpecs: IndexSpecification[],
options: { session?: ClientSession },
callback: MongoCallback<any>,
): void;
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#deleteMany */
deleteMany(filter: FilterQuery<TSchema>, callback: MongoCallback<DeleteWriteOpResultObject>): void;
deleteMany(filter: FilterQuery<TSchema>, options?: CommonOptions): Promise<DeleteWriteOpResultObject>;
deleteMany(
filter: FilterQuery<TSchema>,
options: CommonOptions,
callback: MongoCallback<DeleteWriteOpResultObject>,
): void;
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#deleteOne */
deleteOne(filter: FilterQuery<TSchema>, callback: MongoCallback<DeleteWriteOpResultObject>): void;
deleteOne(
filter: FilterQuery<TSchema>,
options?: CommonOptions & { bypassDocumentValidation?: boolean },
): Promise<DeleteWriteOpResultObject>;
deleteOne(
filter: FilterQuery<TSchema>,
options: CommonOptions & { bypassDocumentValidation?: boolean },
callback: MongoCallback<DeleteWriteOpResultObject>,
): void;
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#distinct */
distinct<Key extends keyof WithId<TSchema>>(
key: Key,
callback: MongoCallback<Array<FlattenIfArray<WithId<TSchema>[Key]>>>,
): void;
distinct<Key extends keyof WithId<TSchema>>(
key: Key,
query: FilterQuery<TSchema>,
callback: MongoCallback<Array<FlattenIfArray<WithId<TSchema>[Key]>>>,
): void;
distinct<Key extends keyof WithId<TSchema>>(
key: Key,
query?: FilterQuery<TSchema>,
options?: MongoDistinctPreferences,
): Promise<Array<FlattenIfArray<WithId<TSchema>[Key]>>>;
distinct<Key extends keyof WithId<TSchema>>(
key: Key,
query: FilterQuery<TSchema>,
options: MongoDistinctPreferences,
callback: MongoCallback<Array<FlattenIfArray<WithId<TSchema>[Key]>>>,
): void;
distinct(key: string, callback: MongoCallback<any[]>): void;
distinct(key: string, query: FilterQuery<TSchema>, callback: MongoCallback<any[]>): void;
distinct(key: string, query?: FilterQuery<TSchema>, options?: MongoDistinctPreferences): Promise<any[]>;
distinct(
key: string,
query: FilterQuery<TSchema>,
options: MongoDistinctPreferences,
callback: MongoCallback<any[]>,
): void;
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#drop */
drop(options?: { session: ClientSession }): Promise<any>;
drop(callback: MongoCallback<any>): void;
drop(options: { session: ClientSession }, callback: MongoCallback<any>): void;
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#dropIndex */
dropIndex(indexName: string, callback: MongoCallback<any>): void;
dropIndex(indexName: string, options?: CommonOptions & { maxTimeMS?: number }): Promise<any>;
dropIndex(indexName: string, options: CommonOptions & { maxTimeMS?: number }, callback: MongoCallback<any>): void;
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#dropIndexes */
dropIndexes(options?: { session?: ClientSession; maxTimeMS?: number }): Promise<any>;
dropIndexes(callback?: MongoCallback<any>): void;
dropIndexes(options: { session?: ClientSession; maxTimeMS?: number }, callback: MongoCallback<any>): void;
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#estimatedDocumentCount */
estimatedDocumentCount(callback: MongoCallback<number>): void;
estimatedDocumentCount(query: FilterQuery<TSchema>, callback: MongoCallback<number>): void;
estimatedDocumentCount(query?: FilterQuery<TSchema>, options?: MongoCountPreferences): Promise<number>;
estimatedDocumentCount(
query: FilterQuery<TSchema>,
options: MongoCountPreferences,
callback: MongoCallback<number>,
): void;
/** http://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html#find */
find<T = TSchema>(query?: FilterQuery<TSchema>): Cursor<T>;
find<T = TSchema>(
query: FilterQuery<TSchema>,
options?: FindOneOptions<T extends TSchema ? TSchema : T>,
): Cursor<T>;
/** http://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html#findOne */
findOne<T = TSchema>(
filter: FilterQuery<TSchema>,
callback: MongoCallback<T extends TSchema ? TSchema : T | null>,
): void;
findOne<T = TSchema>(
filter: FilterQuery<TSchema>,
options?: FindOneOptions<T extends TSchema ? TSchema : T>,
): Promise<T | null>;
findOne<T = TSchema>(
filter: FilterQuery<TSchema>,
options: FindOneOptions<T extends TSchema ? TSchema : T>,
callback: MongoCallback<T extends TSchema ? TSchema : T | null>,
): void;
/** http://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html#findOneAndDelete */
findOneAndDelete(
filter: FilterQuery<TSchema>,
callback: MongoCallback<FindAndModifyWriteOpResultObject<TSchema>>,
): void;
findOneAndDelete(
filter: FilterQuery<TSchema>,
options?: FindOneAndDeleteOption<TSchema>,
): Promise<FindAndModifyWriteOpResultObject<TSchema>>;
findOneAnd