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);
This class is responsible to monitor leaking transactions and automatically
rollback them if the DatabaseSession was garbage collected without commit or rollback. 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/ A handshake happens directly when a connection has been established.
It differs to regular IsMasterCommand in a way that it sends When a tcp/connection issue happened. When the Mongo server returns an error with code,
generally from database.raw or database.query. When a replica member reports 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: In this case we have temporarily a duplicate host 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] Throws the correct ORM errors when responses returns an error https://docs.mongodb.com/manual/reference/operator/query/#query-selectorsClasses
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>;
}
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>;
}
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>);
}
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>;
}
export class MongoQueryModel<T extends OrmEntity> extends DatabaseQueryModel<T, FilterQuery<T>, DEEP_SORT<T>> {
options: CommandOptions;
clone();
getCommandOptions(): CommandOptions;
}
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[]>;
}
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;
}
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;
}
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;
}
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;
}
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>;
}
export class MongoDatabaseTransactionMonitor {
finalizer;
constructor(public logger: Logger);
setLogger(logger: Logger);
}
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();
}
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>;
}
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[]>>;
}
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[]>;
}
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();
}
export abstract class ScramAuth implements MongoAuth {
async auth(command: Command<unknown>, config: MongoClientConfig): Promise<void>;
}
export class Sha1ScramAuth extends ScramAuth {
constructor();
}
export class Sha256ScramAuth extends ScramAuth {
constructor();
}
export class X509Auth implements MongoAuth {
async auth(command: Command<unknown>, config: MongoClientConfig): Promise<void>;
}
export class AbortTransactionCommand extends Command<BaseResponse> {
needsWritableHost();
constructor(private transaction: TransactionalMessage = {});
async execute(config: MongoClientConfig, host: Host, transaction): Promise<BaseResponse>;
}
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;
}
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;
}
export class CommitTransactionCommand extends Command<BaseResponse> {
needsWritableHost();
async execute(config: MongoClientConfig, host: Host, transaction?: MongoDatabaseTransaction): Promise<BaseResponse>;
}
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>;
}
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;
}
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;
}
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;
}
export class DropDatabaseCommand<T> extends Command<void> {
constructor(protected dbName: any);
async execute(config: MongoClientConfig, host: Host, transaction?: MongoDatabaseTransaction): Promise<void>;
needsWritableHost(): boolean;
}
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;
}
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[]>;
}
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;
}
export class HandshakeCommand extends Command<boolean> {
needsWritableHost();
async execute(config: MongoClientConfig, host: Host): Promise<boolean>;
}
client
data as well,
which is only allowed at the first message, and additionally sends auth data if necessary.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;
}
export class IsMasterCommand extends Command<IsMasterResponse> {
needsWritableHost();
async execute(config: MongoClientConfig, host: Host): Promise<IsMasterResponse>;
}
export class StartSessionCommand extends Command<SessionResponse> {
needsWritableHost();
async execute(config: MongoClientConfig, host: Host, transaction?: MongoDatabaseTransaction): Promise<SessionResponse>;
}
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
EventTokenSync<DataEvent<{ pool: MongoConnectionPool; }>>
EventTokenSync<DataEvent<{ pool: MongoConnectionPool; host: Host; }>>
Errors
export class MongoError extends DatabaseError {
readonly code: number;
toString();
}
export class MongoConnectionError extends MongoError {
}
export class MongoDatabaseError extends MongoError {
}
Functions
<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
<T, K extends keyof T>(classType: ClassType<T>, target: FilterQuery<T>, fieldNamesMap?: QueryFieldNames, customMapping?: QueryCustomFields): { [path: string]: any; }
<T extends OrmEntity>(classSchema: ReflectionClass<T>, model: MongoQueryModel<T>): any
(hostname: string): Promise<{ options: string; hosts: { hostname: string; port: number; }[]; }>
(buffer: Uint8Array | ArrayBuffer, offset?: number): number
(config: MongoClientConfig): void
(config: MongoClientConfig): Host[]
hosts
in a heartbeat, we have to make sure to update our known hosts.
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.hostname
is what the replica member reports as me
.
We use hostname as Host.id.(hosts: Host[]): Topology
(response: BaseResponse): DatabaseError | undefined
(error: any): boolean
(error: any): boolean
<Request extends { [name: string]: any; }, Response>(request: Request | ((config: MongoClientConfig) => Request), optionsIn?: Partial<CreateCommandOptions>, typeRequest?: ReceiveType<Request>, typeResponse?: ReceiveType<Response>): Command<Response & BaseResponse>
Types
type MongoExplainVerbosity = 'queryPlanner' | 'executionStats' | 'allPlansExecution';
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;
};
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;
};
type ObjectQuerySelector<T> = T extends object ? { [key in keyof T]?: QuerySelector<T[key]> } : QuerySelector<T>;
type Condition<T> = MongoAltQuery<T> | QuerySelector<MongoAltQuery<T>>;
type FilterQuery<T> = {
[P in keyof T]?: Condition<T[P]>;
} &
RootQuerySelector<T>;
type SORT_TYPE = SORT_ORDER | { $meta: 'textScore' };
type DEEP_SORT<T extends OrmEntity> = { [P in keyof T]?: SORT_TYPE } & { [P: string]: SORT_TYPE };
type HostType =
'unknown' |
'standalone' |
'primary' |
'secondary' |
'mongos' |
'arbiter' |
'other' |
'ghost';
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'];
}
type Topology = 'single' | 'replicaSetNoPrimary' | 'replicaSetWithPrimary' | 'sharded' | 'unknown' | 'invalidated';
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;
}
interface MongoAuth {
auth(command: Command<unknown>, config: MongoClientConfig): Promise<void>;
}
interface BaseResponse {
ok: number;
errmsg?: string;
code?: number;
codeName?: string;
writeErrors?: Array<{ index: number, code: number, errmsg: string }>;
}
interface TransactionalMessage {
abortTransaction?: 1;
commitTransaction?: 1;
lsid?: { id: UUID };
txnNumber?: bigint;
startTransaction?: boolean;
autocommit?: boolean;
}
interface WriteConcernMessage {
writeConcern?: { w?: string | number, j?: boolean, wtimeout?: number };
}
interface CollationMessage {
locale: string;
caseLevel?: boolean;
caseFirst?: string;
strength?: number;
numericOrdering?: boolean;
alternate?: string;
maxVariable?: string;
backwards?: boolean;
}
type HintMessage = string | {
[name: string]: number;
};
interface ReadPreferenceMessage {
readConcern?: { level: ConnectionOptions['readConcernLevel'] };
$readPreference?: {
mode: ConnectionOptions['readPreference'];
tags?: { [name: string]: string }[];
maxStalenessSeconds?: number;
hedge?: { enabled: boolean }
};
}
interface CreateIndex {
key: { [name: string]: 1 },
name: string,
unique: boolean,
sparse: boolean,
expireAfterSeconds?: number
}
type GetMoreMessage = {
getMore: bigint;
$db: string;
collection: string;
batchSize?: number;
maxTimeMS?: number;
comment?: string;
} & TransactionalMessage & ReadPreferenceMessage;
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;
}