github
DocsBlog
fontcolor_theme
package

API @deepkit/mongo

npm install @deepkit/mongo

Standalone MongoDB driver and a database adapter for Deepkit ORM.

import { MongoDatabaseAdapter } from '@deepkit/mongo';
import { Database } from '@deepkit/orm';

const adapter = new MongoDatabaseAdapter('mongodb://localhost:27017/mydatabase');

const database = new Database(adapter);

Classes

MongoDatabaseQueryFactory [source]
export class MongoDatabaseQueryFactory extends DatabaseAdapterQueryFactory {
    constructor(private client: MongoClient, private databaseSession: DatabaseSession<any>);
    createQuery<T extends OrmEntity>(type?: ReceiveType<T> | ClassType<T> | AbstractClassType<T> | ReflectionClass<T>): MongoDatabaseQuery<T>;
}
MongoRawFactory [source]
export class MongoRawFactory implements RawFactory<[
    Command<any>
]> {
    constructor(protected session: DatabaseSession<MongoDatabaseAdapter>, protected client: MongoClient);
    create<Entity = any, ResultSchema = Entity>(commandOrPipeline: Command<ResultSchema> | any[], type?: ReceiveType<Entity>, resultType?: ReceiveType<ResultSchema>): MongoRawCommandQuery<ResultSchema>;
}
MongoDatabaseAdapter [source]
export class MongoDatabaseAdapter extends DatabaseAdapter {
    readonly client: MongoClient;
    transactionMonitor: MongoDatabaseTransactionMonitor;
    constructor(connection: string | MongoClient);
    setEventDispatcher(eventDispatcher: EventDispatcher);
    setLogger(logger: Logger);
    rawFactory(session: DatabaseSession<this>): MongoRawFactory;
    getName(): string;
    getSchemaName(): string;
    createPersistence(session: DatabaseSession<this>): MongoPersistence;
    createTransaction(session: DatabaseSession<this>): MongoDatabaseTransaction;
    isNativeForeignKeyConstraintSupported();
    queryFactory(databaseSession: DatabaseSession<any>): MongoDatabaseQueryFactory;
    disconnect(force?: boolean): void;
    getAutoIncrementSequencesCollection(): string;
    async resetAutoIncrementSequences();
    async migrate(options: MigrateOptions, entityRegistry: DatabaseEntityRegistry);
    async migrateClassSchema(options: MigrateOptions, schema: ReflectionClass<any>);
}
MongoPersistence [source]
export class MongoPersistence extends DatabasePersistence {
    commandOptions: CommandOptions;
    constructor(protected client: MongoClient, protected ormSequences: ReflectionClass<any>, protected session: DatabaseSession<any>);
    release();
    async getConnection(): Promise<MongoConnection>;
    handleSpecificError(error: Error): Error;
    async remove<T extends OrmEntity>(classSchema: ReflectionClass<T>, items: T[]): Promise<void>;
    async insert<T extends OrmEntity>(classSchema: ReflectionClass<T>, items: T[]): Promise<void>;
    async update<T extends OrmEntity>(classSchema: ReflectionClass<T>, changeSets: DatabasePersistenceChangeSet<T>[]): Promise<void>;
}
MongoQueryModel [source]
export class MongoQueryModel<T extends OrmEntity> extends DatabaseQueryModel<T, FilterQuery<T>, DEEP_SORT<T>> {
    options: CommandOptions;
    clone();
    getCommandOptions(): CommandOptions;
}
MongoQueryResolver [source]
export class MongoQueryResolver<T extends OrmEntity> extends GenericQueryResolver<T, DatabaseAdapter, MongoQueryModel<T>> {
    constructor(classSchema: ReflectionClass<T>, protected session: DatabaseSession<MongoDatabaseAdapter>, protected client: MongoClient);
    async has(model: MongoQueryModel<T>): Promise<boolean>;
    async explain(model: MongoQueryModel<T>, op: QueryExplainOp, option: MongoExplainVerbosity = ): Promise<MongoExplain>;
    handleSpecificError(error: Error): Error;
    async delete(queryModel: MongoQueryModel<T>, deleteResult: DeleteResult<T>): Promise<void>;
    async patch(model: MongoQueryModel<T>, changes: Changes<T>, patchResult: PatchResult<T>): Promise<void>;
    async count(queryModel: MongoQueryModel<T>);
    async findOneOrUndefined(model: MongoQueryModel<T>): Promise<T | undefined>;
    async find(model: MongoQueryModel<T>): Promise<T[]>;
}
MongoDatabaseQuery [source]
export class MongoDatabaseQuery<T extends OrmEntity> extends Query<T> {
    model: MongoQueryModel<T>;
    resolver: MongoQueryResolver<T>;
    /**
     * Sets Mongo specific options for this query like `collation`, `hint`, `readPreference`, `allowDiskUse` and more.
     */
    withOptions(options: CommandOptions): this;
}
HostStats [source]
export class HostStats {
    /**
     * How many connections were created to this host.
     */
    connectionsCreated: number;
    connectionsReused: number;
    connectionsError: number;
    connectionsQueued: number;
    connectionsAlive: number;
    connectionsReserved: number;
    commandsActive: number;
    commandsExecuted: number;
    commandsFailed: number;
    bytesReceived: number;
    bytesSent: number;
    heartbeats: number;
    heartbeatsFailed: number;
}
Host [source]
export class Host {
    /**
     * The real unique id of the host. This is the host returned by the server.
     */
    id: string;
    type: HostType;
    status: string;
    readonly connections: MongoConnection[];
    replicaSetName?: string;
    tags: {
        [name: string]: string;
    };
    /**
     * True if the server is `mongos,
     * or node is in recovering, startup, or rollback mode.
     */
    readonly: boolean;
    /**
     * True if the server cannot be reached (heartbeat failed).
     */
    dead: boolean;
    /**
     * Average latency in ms (used for `nearest`)
     *
     * Round Trip Times of the heartbeat (`ismaster`) command.
     */
    latency: number;
    hosts: string[];
    passives: string[];
    arbiters: string[];
    subsequentHeartbeatErrors: number;
    passive: boolean;
    hidden: boolean;
    lastWriteDate?: Date;
    lastUpdateTime?: Date;
    lastUpdatePromise?: Promise<void>;
    /**
     * Calculate staleness in milliseconds.
     */
    staleness: number;
    stale: boolean;
    stats: HostStats;
    /**
     * This is either the hostname from configuration or found in the `ismaster` result.
     */
    constructor(public hostname: string, public port: number = );
    get label(): string;
    get freeConnections(): number;
    isWritable(): boolean;
    isReadable(): boolean;
    isUsable(): boolean;
    setType(type: HostType);
    getType();
    getTypeFromIsMasterResult(isMasterCmdResult: any): HostType;
}
MongoStats [source]
export class MongoStats {
    /**
     * How many connections have been created.
     */
    connectionsCreated: number;
    connectionsError: number;
    /**
     * How many connections have been reused.
     */
    connectionsReused: number;
    /**
     * How many connection requests were queued because pool was full.
     */
    connectionsQueued: number;
    bytesReceived: number;
    bytesSent: number;
    heartbeats: number;
    heartbeatsFailed: number;
    topologyChanges: number;
}
MongoConnectionPool [source]
export class MongoConnectionPool {
    closed: boolean;
    /**
     * Connections, might be in any state, not necessarily connected.
     */
    connections: MongoConnection[];
    constructor(protected config: MongoClientConfig, protected serializer: BSONBinarySerializer, protected stats: MongoStats, public logger: Logger, public eventDispatcher: EventDispatcher);
    async connect();
    /**
     * Returns true when at least one primary or secondary host is connected.
     */
    isConnected(): boolean;
    /**
     * Returns true when at least one connection is writable.
     */
    isWritable(): boolean;
    getConnectedConnections(): MongoConnection[];
    close();
    /**
     * Explores the topology and updates the known hosts.
     */
    heartbeat(force: boolean = false): void;
    /**
     * Returns an existing or new connection, that needs to be released once done using it.
     */
    async getConnection(partialRequest: Partial<ConnectionRequest> = {}): Promise<MongoConnection>;
}
MongoDatabaseTransactionMonitor [source]
export class MongoDatabaseTransactionMonitor {
    finalizer;
    constructor(public logger: Logger);
    setLogger(logger: Logger);
}

This class is responsible to monitor leaking transactions and automatically rollback them if the DatabaseSession was garbage collected without commit or rollback.

MongoDatabaseTransaction [source]
export class MongoDatabaseTransaction extends DatabaseTransaction {
    commandOptions: CommandOptions;
    static txnNumber: bigint;
    connection?: MongoConnection;
    lsid?: {
        id: string;
    };
    txnNumber: bigint;
    started: boolean;
    constructor(protected monitor: MongoDatabaseTransactionMonitor);
    with(commandOptions: CommandOptions): this;
    applyTransaction(cmd: TransactionalMessage);
    async begin();
    async commit();
    async rollback();
}
MongoConnection [source]
export class MongoConnection {
    status: MongoConnectionStatus;
    connectingPromise?: Promise<void>;
    lastCommand?: {
        command: Command<unknown>;
        promise?: Promise<any>;
    };
    activeCommands: number;
    executedCommands: number;
    activeTransaction: boolean;
    reserved: boolean;
    cleanupTimeout?: ReturnType<typeof setTimeout>;
    transaction?: WeakRef<MongoDatabaseTransaction>;
    responseParser: BsonStreamReader;
    error?: Error;
    bytesReceived: number;
    bytesSent: number;
    closed: boolean;
    constructor(public id: number, public host: Host, protected config: MongoClientConfig, protected serializer: BSONBinarySerializer, protected onClose: (connection: MongoConnection) => void, protected onRelease: (connection: MongoConnection) => void, protected onSent: (bytes: number) => void, protected onReceived: (bytes: number) => void);
    isConnected();
    isConnecting();
    close();
    release();
    /**
     * Puts a command on the queue and executes it when queue is empty.
     * A promises is return that is resolved with the  when executed successfully, or rejected
     * when timed out, parser error, or any other error.
     */
    async execute<T extends Command<unknown>>(command: T): Promise<ReturnType<T[]>>;
    async connect(): Promise<void>;
}
MongoClient [source]
export class MongoClient {
    readonly config: MongoClientConfig;
    pool: MongoConnectionPool;
    stats: MongoStats;
    constructor(connectionString: string, public eventDispatcher: EventDispatcher = new EventDispatcher(), public logger: Logger = new ConsoleLogger());
    setLogger(logger: Logger);
    setEventDispatcher(eventDispatcher: EventDispatcher);
    resolveCollectionName(schema: ReflectionClass<any>): string;
    async connect();
    close();
    async dropDatabase(dbName: string): Promise<void>;
    /**
     * Returns an existing or new connection, that needs to be released once done using it.
     */
    async getConnection(request: Partial<ConnectionRequest> = {}, transaction?: MongoDatabaseTransaction): Promise<MongoConnection>;
    async execute<T extends Command<unknown>>(command: T, request: Partial<ConnectionRequest> = {}, transaction?: MongoDatabaseTransaction): Promise<ReturnType<T[]>>;
}
MongoClientConfig [source]
export class MongoClientConfig {
    topology: Topology;
    topologyId: number;
    readonly hosts: Host[];
    defaultDb?: string;
    authUser?: string;
    authPassword?: string;
    options: ConnectionOptions;
    isSrv: boolean;
    srvDomain: string;
    lastTopologyKey: string;
    constructor(connectionString: string);
    /**
     * Unique representation of a topology. If this changes, the topology has changed.
     * Topology change happens when:
     *
     * - A new host is added
     * - A host is removed
     * - A host changes its type
     * - A host is marked as dead
     * - A host is marked as stale
     */
    topologyKey(): string;
    shortSummary(): string;
    invalidate();
    getTopology(): string;
    /**
     * Applies the write concern to the command.
     *
     * This must not be called in a transaction for normal commands, since only
     * commitTransaction/abortTransaction commands are allowed to set writeConcern.
     */
    applyWriteConcern(cmd: WriteConcernMessage, options: CommandOptions);
    /**
     * @see https://github.com/mongodb/specifications/blob/master/source/server-selection/server-selection.md#passing-read-preference-to-mongos-and-load-balancers
     */
    applyReadPreference(host: Host, cmd: ReadPreferenceMessage & TransactionalMessage, options: CommandOptions, transaction?: MongoDatabaseTransaction);
    getAuthSource(): string;
    newHost(hostname: string, port: number);
    deleteHost(hostname: string, port: number);
    resolveCollectionName(schema: ReflectionClass<any>): string;
    async getHosts(): Promise<Host[]>;
}

Default URL: mongodb://mongodb0.example.com:27017

ReplicaSet UR: mongodb://mongodb0.example.com:27017,mongodb1.example.com:27017,mongodb2.example.com:27017/?replicaSet=myRepl

Shared URL: mongodb://mongos0.example.com:27017,mongos1.example.com:27017,mongos2.example.com:27017

SVR URL: mongodb+srv://server.example.com/

ConnectionOptions [source]
export class ConnectionOptions {
    /**
     * The replica set name.
     */
    replicaSet?: string;
    /**
     * TCP connection timeout. Default 30s.
     *
     * If the socket connect takes longer than this value, the connection is aborted.
     */
    connectTimeoutMS: Milliseconds;
    /**
     * TCP socket timeout. Default not set.
     *
     * If greater than 0 `Socket.setTimeout()` will be called.
     */
    socketTimeoutMS: Milliseconds;
    /**
     * The interval in milliseconds between the heartbeat checks. Default 10s.
     */
    heartbeatFrequencyMS: Milliseconds;
    /**
     * The maximum number of connections in the connection pool
     * How many connections per host are allowed on the pool.
     * If this limit is reached, the connection acquisition waits until a connection is released.
     * See also `connectionAcquisitionTimeout`.
     */
    maxPoolSize: number;
    /**
     * The minimum number of connections in the connection pool.
     */
    minPoolSize: number;
    /**
     * The maximum time in milliseconds that a thread can wait for a connection to become available
     */
    waitQueueTimeoutMS: Milliseconds;
    /**
     * Close a connection after it has been idle for this duration.
     * Default 60s.
     */
    maxIdleTimeMS: Milliseconds;
    /**
     * The maximum staleness to allow in milliseconds. Default 0 (no staleness check).
     *
     * I define this must be minimum 90 seconds:
     *    `heartbeatFrequency`+`idleWritePeriodMS` (10"000ms from the spec).
     *
     * Don't choose too low value to ensure secondaries are not considered stale too aggressively.
     */
    maxStalenessSeconds: number;
    /**
     * Command response timeout. Default 0.
     *
     * If greater than 0, the command is aborted if it takes longer than this value
     * to answer. This might be tricky if you have very long-running queries.
     */
    commandTimeoutMS: Milliseconds;
    /**
     * @see https://www.mongodb.com/docs/manual/reference/write-concern/#std-label-wc-j
     */
    w?: string | number;
    /**
     * If true the client sends operations to only the specified host.
     * It doesn't attempt to discover any other members of the replica set.
     */
    directConnection: boolean;
    /**
     * Write concern timeout in milliseconds.
     *
     * @see https://www.mongodb.com/docs/manual/reference/write-concern/#wtimeout
     */
    wtimeout?: Milliseconds;
    journal?: boolean;
    appName?: string;
    /**
     * If set, this is used for all find commands.
     */
    allowDiskUse?: boolean;
    retryWrites: boolean;
    retryReads: boolean;
    readConcernLevel?:  |  |  |  | ;
    readPreference?:  |  |  |  | ;
    readPreferenceTags?: string;
    hedge?: boolean;
    authSource?: string;
    authMechanism?:  |  |  |  | ;
    authMechanismProperties?: string;
    gssapiServiceName?: string;
    batchSize: number;
    ssl?: boolean;
    tlsCertificateFile?: string;
    tlsCertificateKeyFile?: string;
    tlsCertificateKeyFilePassword?: string;
    tlsCAFile?: string;
    tlsCRLFile?: string;
    tlsAllowInvalidCertificates?: boolean;
    tlsAllowInvalidHostnames?: boolean;
    tlsInsecure?: boolean;
    /**
     * In seconds.
     */
    srvCacheTimeout: number;
    validate();
    parsePreferenceTags(tags: string): {
        [name: string]: string;
    }[];
    getAuthMechanismProperties(): AuthMechanismProperties;
    get checkServerIdentity();
    get rejectUnauthorized();
    get secondaryReadAllowed();
}
ScramAuth [source]
export abstract class ScramAuth implements MongoAuth {
    async auth(command: Command<unknown>, config: MongoClientConfig): Promise<void>;
}
Sha1ScramAuth [source]
export class Sha1ScramAuth extends ScramAuth {
    constructor();
}
Sha256ScramAuth [source]
export class Sha256ScramAuth extends ScramAuth {
    constructor();
}
X509Auth [source]
export class X509Auth implements MongoAuth {
    async auth(command: Command<unknown>, config: MongoClientConfig): Promise<void>;
}
AbortTransactionCommand [source]
export class AbortTransactionCommand extends Command<BaseResponse> {
    needsWritableHost();
    constructor(private transaction: TransactionalMessage = {});
    async execute(config: MongoClientConfig, host: Host, transaction): Promise<BaseResponse>;
}
AggregateCommand [source]
export class AggregateCommand<T, R = BaseResponse> extends Command<R[]> {
    partial: boolean;
    constructor(public schema: ReflectionClass<T>, public pipeline: any[] = [], public resultSchema?: ReflectionClass<R> | Type);
    getCommand(config: MongoClientConfig, host: Host, transaction?: MongoDatabaseTransaction);
    async execute(config: MongoClientConfig, host: Host, transaction?: MongoDatabaseTransaction): Promise<R[]>;
    needsWritableHost(): boolean;
}
Command [source]
export abstract class Command<T> {
    options: CommandOptions;
    sender?: <T>(schema: Type, message: T) => void;
    reject(error: Error): void;
    sendAndWait<T, R extends BaseResponse = BaseResponse>(message: T, messageType?: ReceiveType<T>, responseType?: ReceiveType<R>): Promise<R>;
    abstract execute(config: MongoClientConfig, host: Host, transaction?: MongoDatabaseTransaction): Promise<T>;
    needsWritableHost(): boolean;
    handleResponse(response: Uint8Array): void;
}
CommitTransactionCommand [source]
export class CommitTransactionCommand extends Command<BaseResponse> {
    needsWritableHost();
    async execute(config: MongoClientConfig, host: Host, transaction?: MongoDatabaseTransaction): Promise<BaseResponse>;
}
CountCommand [source]
export class CountCommand<T extends ReflectionClass<any>> extends Command<number> {
    constructor(public schema: T, public query: {
        [name: string]: any;
    } = {}, public limit: number = , public skip: number = );
    getCommand(config: MongoClientConfig, host: Host, transaction?: MongoDatabaseTransaction);
    async execute(config: MongoClientConfig, host: Host, transaction?: MongoDatabaseTransaction): Promise<number>;
}
CreateCollectionCommand [source]
export class CreateCollectionCommand<T extends ReflectionClass<any>> extends Command<void> {
    constructor(public schema: T);
    async execute(config: MongoClientConfig, host: Host, transaction?: MongoDatabaseTransaction): Promise<void>;
    needsWritableHost(): boolean;
}
CreateIndexesCommand [source]
export class CreateIndexesCommand<T extends ReflectionClass<any>> extends Command<void> {
    constructor(public schema: T, public indexes: CreateIndex[]);
    async execute(config: MongoClientConfig, host: Host, transaction?: MongoDatabaseTransaction): Promise<void>;
    needsWritableHost(): boolean;
}
DeleteCommand [source]
export class DeleteCommand<T extends ReflectionClass<any>> extends Command<number> {
    constructor(public schema: T, public filter: {
        [name: string]: any;
    } = {}, public limit: number = , public skip: number = );
    async execute(config: MongoClientConfig, host: Host, transaction?: MongoDatabaseTransaction): Promise<number>;
    needsWritableHost(): boolean;
}
DropDatabaseCommand [source]
export class DropDatabaseCommand<T> extends Command<void> {
    constructor(protected dbName: any);
    async execute(config: MongoClientConfig, host: Host, transaction?: MongoDatabaseTransaction): Promise<void>;
    needsWritableHost(): boolean;
}
DropIndexesCommand [source]
export class DropIndexesCommand<T extends ReflectionClass<any>> extends Command<void> {
    constructor(public schema: T, public names: string[]);
    async execute(config: MongoClientConfig, host: Host, transaction?: MongoDatabaseTransaction): Promise<void>;
    needsWritableHost(): boolean;
}
FindCommand [source]
export class FindCommand<T> extends Command<T[]> {
    constructor(public schema: ReflectionClass<T>, public filter: {
        [name: string]: any;
    } = {}, public projection?: {
        [name: string]:  | ;
    }, public sort?: DEEP_SORT<any>, public limit: number = , public skip: number = );
    getCommand(config: MongoClientConfig, host: Host, transaction?: MongoDatabaseTransaction);
    async execute(config: MongoClientConfig, host: Host, transaction?: MongoDatabaseTransaction): Promise<T[]>;
}
FindAndModifyCommand [source]
export class FindAndModifyCommand<T extends ReflectionClass<any>> extends Command<FindAndModifyResponse> {
    upsert;
    fields: string[];
    returnNew: boolean;
    constructor(public schema: T, public query: any, public update: any);
    getCommand(config: MongoClientConfig, host: Host, transaction?: MongoDatabaseTransaction);
    async execute(config: MongoClientConfig, host: Host, transaction?: MongoDatabaseTransaction): Promise<FindAndModifyResponse>;
    needsWritableHost(): boolean;
}
HandshakeCommand [source]
export class HandshakeCommand extends Command<boolean> {
    needsWritableHost();
    async execute(config: MongoClientConfig, host: Host): Promise<boolean>;
}

A handshake happens directly when a connection has been established. It differs to regular IsMasterCommand in a way that it sends client data as well, which is only allowed at the first message, and additionally sends auth data if necessary.

InsertCommand [source]
export class InsertCommand<T> extends Command<number> {
    constructor(protected schema: ReflectionClass<T>, protected documents: T[]);
    async execute(config: MongoClientConfig, host: Host, transaction?: MongoDatabaseTransaction): Promise<number>;
    needsWritableHost(): boolean;
}
IsMasterCommand [source]
export class IsMasterCommand extends Command<IsMasterResponse> {
    needsWritableHost();
    async execute(config: MongoClientConfig, host: Host): Promise<IsMasterResponse>;
}
StartSessionCommand [source]
export class StartSessionCommand extends Command<SessionResponse> {
    needsWritableHost();
    async execute(config: MongoClientConfig, host: Host, transaction?: MongoDatabaseTransaction): Promise<SessionResponse>;
}
UpdateCommand [source]
export class UpdateCommand<T extends ReflectionClass<any>> extends Command<number> {
    constructor(public schema: T, public updates: {
        q: any;
        u: any;
        multi: boolean;
    }[] = []);
    getCommand(config: MongoClientConfig, host: Host, transaction?: MongoDatabaseTransaction);
    async execute(config: MongoClientConfig, host: Host, transaction?: MongoDatabaseTransaction): Promise<number>;
    needsWritableHost(): boolean;
}

Events

onMongoTopologyChange [source]
EventTokenSync<DataEvent<{ pool: MongoConnectionPool; }>>
onMongoNewHost [source]
EventTokenSync<DataEvent<{ pool: MongoConnectionPool; host: Host; }>>

Errors

MongoError [source]
export class MongoError extends DatabaseError {
    readonly code: number;
    toString();
}
MongoConnectionError [source]
export class MongoConnectionError extends MongoError {
}

When a tcp/connection issue happened.

MongoDatabaseError [source]
export class MongoDatabaseError extends MongoError {
}

When the Mongo server returns an error with code, generally from database.raw or database.query.

Functions

convertClassQueryToMongo [source]
<T, K extends keyof T, Q extends FilterQuery<T>>(classType: ReflectionClass<T> | ClassType, query: Q, fieldNamesMap?: QueryFieldNames, customMapping?: { [name: string]: (name: string, value: any, fieldNamesMap: { [name: string]: boolean; }) => any; }): Q
convertPlainQueryToMongo [source]
<T, K extends keyof T>(classType: ClassType<T>, target: FilterQuery<T>, fieldNamesMap?: QueryFieldNames, customMapping?: QueryCustomFields): { [path: string]: any; }
getMongoFilter [source]
<T extends OrmEntity>(classSchema: ReflectionClass<T>, model: MongoQueryModel<T>): any
resolveSrvHosts [source]
(hostname: string): Promise<{ options: string; hosts: { hostname: string; port: number; }[]; }>
readUint32LE [source]
(buffer: Uint8Array | ArrayBuffer, offset?: number): number
updateStaleness [source]
(config: MongoClientConfig): void
updateKnownHosts [source]
(config: MongoClientConfig): Host[]

When a replica member reports hosts in a heartbeat, we have to make sure to update our known hosts.

This removes also duplicate hosts.

Use-cases: The user specified IP, but the nodes are known under hostnames config = mongodb://192.168.0.2,192.168.0.3 hostnames = [server1, server2]

Resolving stage:

  1. initial user config: config.hosts=[192.168.0.2,192.168.0.3] (Host.id[])
  2. heartbeat(192.168.0.2), reporting me=server1, hosts=[server1, server2], rename id=192.168.0.2 to server1
  3. updateKnownHosts(): server2 is new. config.hosts=[server1, 192.168.0.3, server2]
  4. heartbeat(192.168.0.3), reporting me=server1, hosts=[server1, server2], rename id=192.168.0.3 to server2
  5. heartbeat(server2), reporting me=server2, hosts=[server1, server2], detected as duplicate, remove, config.hosts=[server1, server2]

In this case we have temporarily a duplicate host server2, since at point 3 the heartbeat of 192.168.0.3 was not finished yet. This is fine, since we remove duplicates in the end after asking 192.168.0.3 what its real hostname is.

Use-case: The user specified hostnames, but the nodes are known under IPs config = mongodb://server1,server2 hostname = [192.168.0.2, 192.168.0.3]

hostname is what the replica member reports as me. We use hostname as Host.id.

detectTopology [source]
(hosts: Host[]): Topology
handleErrorResponse [source]
(response: BaseResponse): DatabaseError | undefined

Throws the correct ORM errors when responses returns an error

isErrorRetryableWrite [source]
(error: any): boolean
isErrorRetryableRead [source]
(error: any): boolean
createCommand [source]
<Request extends { [name: string]: any; }, Response>(request: Request | ((config: MongoClientConfig) => Request), optionsIn?: Partial<CreateCommandOptions>, typeRequest?: ReceiveType<Request>, typeResponse?: ReceiveType<Response>): Command<Response & BaseResponse>

Types

MongoExplainVerbosity [source]
type MongoExplainVerbosity = 'queryPlanner' | 'executionStats' | 'allPlansExecution';
QuerySelector [source]
type QuerySelector<T> = {
    // Comparison
    $eq?: T;
    $gt?: T;
    $gte?: T;
    $in?: T[];
    $lt?: T;
    $lte?: T;
    $ne?: T;
    $nin?: T[];
    // Logical
    $not?: T extends string ? (QuerySelector<T> | RegExp) : QuerySelector<T>;
    // Element
    /**
     * When `true`, `$exists` matches the documents that contain the field,
     * including documents where the field value is null.
     */
    $exists?: boolean;
    $type?: number | BSONTypeAlias;
    // Evaluation
    $expr?: any;
    $jsonSchema?: any;
    $mod?: T extends number ? [number, number] : never;
    $regex?: T extends string ? (RegExp | string) : never;
    $options?: T extends string ? string : never;
    // Geospatial
    // TODO: define better types for geo queries
    $geoIntersects?: { $geometry: object };
    $geoWithin?: object;
    $near?: object;
    $nearSphere?: object;
    $maxDistance?: number;
    // Array
    // TODO: define better types for $all and $elemMatch
    $all?: T extends Array<infer U> ? any[] : never;
    $elemMatch?: T extends Array<infer U> ? object : never;
    $size?: T extends Array<infer U> ? number : never;
    // Bitwise
    $bitsAllClear?: BitwiseQuery;
    $bitsAllSet?: BitwiseQuery;
    $bitsAnyClear?: BitwiseQuery;
    $bitsAnySet?: BitwiseQuery;

    //special deepkit/type type
    $parameter?: string;
};

https://docs.mongodb.com/manual/reference/operator/query/#query-selectors

RootQuerySelector [source]
type RootQuerySelector<T> = {
    /** https://docs.mongodb.com/manual/reference/operator/query/and/#op._S_and */
    $and?: Array<FilterQuery<T>>;
    /** https://docs.mongodb.com/manual/reference/operator/query/nor/#op._S_nor */
    $nor?: Array<FilterQuery<T>>;
    /** https://docs.mongodb.com/manual/reference/operator/query/or/#op._S_or */
    $or?: Array<FilterQuery<T>>;
    /** https://docs.mongodb.com/manual/reference/operator/query/text */
    $text?: {
        $search: string;
        $language?: string;
        $caseSensitive?: boolean;
        $diacraticSensitive?: boolean;
    };
    /** https://docs.mongodb.com/manual/reference/operator/query/where/#op._S_where */
    $where?: string | Function;
    /** https://docs.mongodb.com/manual/reference/operator/query/comment/#op._S_comment */
    $comment?: string;

    // we could not find a proper TypeScript generic to support nested queries e.g. 'user.friends.name'
    // this will mark all unrecognized properties as any (including nested queries)
    [key: string]: UUID | MongoId | any;
};
ObjectQuerySelector [source]
type ObjectQuerySelector<T> = T extends object ? { [key in keyof T]?: QuerySelector<T[key]> } : QuerySelector<T>;
Condition [source]
type Condition<T> = MongoAltQuery<T> | QuerySelector<MongoAltQuery<T>>;
FilterQuery [source]
type FilterQuery<T> = {
    [P in keyof T]?: Condition<T[P]>;
} &
    RootQuerySelector<T>;
SORT_TYPE [source]
type SORT_TYPE = SORT_ORDER | { $meta: 'textScore' };
DEEP_SORT [source]
type DEEP_SORT<T extends OrmEntity> = { [P in keyof T]?: SORT_TYPE } & { [P: string]: SORT_TYPE };
HostType [source]
type HostType =
    'unknown' |
    'standalone' |
    'primary' |
    'secondary' |
    'mongos' |
    'arbiter' |
    'other' |
    'ghost';
ConnectionRequest [source]
interface ConnectionRequest {
    /**
     * When set to true, connections to a primary are returned.
     *
     * Is set to true automatically when a write operation is executed.
     *
     * Default is false.
     */
    writable: boolean;

    readPreference: ConnectionOptions['readPreference'];

    readPreferenceTags?: ConnectionOptions['readPreferenceTags'];
}
Topology [source]
type Topology = 'single' | 'replicaSetNoPrimary' | 'replicaSetWithPrimary' | 'sharded' | 'unknown' | 'invalidated';
CommandOptions [source]
interface CommandOptions {
    batchSize?: number;
    readPreference?: ConnectionOptions['readPreference'];
    readPreferenceTags?: string;
    readConcernLevel?: ConnectionOptions['readConcernLevel'];

    writeConcern?: string | number;
    journal?: boolean;
    wtimeout?: number;

    allowDiskUse?: boolean;

    hint?: HintMessage;
    collation?: CollationMessage;
}
MongoAuth [source]
interface MongoAuth {
    auth(command: Command<unknown>, config: MongoClientConfig): Promise<void>;
}
BaseResponse [source]
interface BaseResponse {
    ok: number;
    errmsg?: string;
    code?: number;
    codeName?: string;
    writeErrors?: Array<{ index: number, code: number, errmsg: string }>;
}
TransactionalMessage [source]
interface TransactionalMessage {
    abortTransaction?: 1;
    commitTransaction?: 1;

    lsid?: { id: UUID };
    txnNumber?: bigint;
    startTransaction?: boolean;
    autocommit?: boolean;
}
WriteConcernMessage [source]
interface WriteConcernMessage {
    writeConcern?: { w?: string | number, j?: boolean, wtimeout?: number };
}
CollationMessage [source]
interface CollationMessage {
    locale: string;
    caseLevel?: boolean;
    caseFirst?: string;
    strength?: number;
    numericOrdering?: boolean;
    alternate?: string;
    maxVariable?: string;
    backwards?: boolean;
}
HintMessage [source]
type HintMessage = string | {
    [name: string]: number;
};
ReadPreferenceMessage [source]
interface ReadPreferenceMessage {
    readConcern?: { level: ConnectionOptions['readConcernLevel'] };

    $readPreference?: {
        mode: ConnectionOptions['readPreference'];
        tags?: { [name: string]: string }[];
        maxStalenessSeconds?: number;
        hedge?: { enabled: boolean }
    };
}
CreateIndex [source]
interface CreateIndex {
    key: { [name: string]: 1 },
    name: string,
    unique: boolean,
    sparse: boolean,
    expireAfterSeconds?: number
}
GetMoreMessage [source]
type GetMoreMessage = {
    getMore: bigint;
    $db: string;
    collection: string;
    batchSize?: number;
    maxTimeMS?: number;
    comment?: string;
} & TransactionalMessage & ReadPreferenceMessage;
IsMasterResponse [source]
interface IsMasterResponse extends BaseResponse {
    ismaster: number;
    maxBsonObjectSize: number;
    maxMessageSizeBytes: number;
    maxWriteBatchSize: number;
    minWireVersion: number;
    maxWireVersion: number;

    //indicates that the mongod or mongos is running in read-only mode
    readOnly?: boolean;


    compression?: string[];
    saslSupportedMechs?: string[];

    //mongos instances add the following field to the isMaster response document:
    msg?: string;

    //isMaster contains these fields when returned by a member of a replica set:
    hosts?: string[];
    passives?: string[];
    setName?: string; //replica set name
    // setVersion: number; //replica set version
    me?: string;
    secondary?: boolean;
    arbiterOnly?: boolean;
    hidden?: boolean;

    lastWrite?: {
        lastWriteDate: Date;
    };

    [k: string]: any;
}