declare module 'mongoose' {
import mongodb = require('mongodb');
import events = require('events');
const connection: Connection;
const connections: Connection[];
function connect(uri: string, options?: ConnectOptions): Promise<Mongoose>;
function createConnection(uri: string, options?: ConnectOptions): Connection;
function createConnection(): Connection;
function disconnect(): Promise<void>;
* Connection ready state
*
* - 0 = disconnected
* - 1 = connected
* - 2 = connecting
* - 3 = disconnecting
* - 99 = uninitialized
*/
enum ConnectionStates {
disconnected = 0,
connected = 1,
connecting = 2,
disconnecting = 3,
uninitialized = 99,
}
const STATES: typeof ConnectionStates;
interface ConnectOptions extends mongodb.MongoClientOptions {
bufferCommands?: boolean;
dbName?: string;
user?: string;
pass?: string;
autoIndex?: boolean;
autoCreate?: boolean;
* Sanitizes query filters against [query selector injection attacks](
* https://thecodebarbarian.com/2014/09/04/defending-against-query-selector-injection-attacks.html
* ) by wrapping any nested objects that have a property whose name starts with $ in a $eq.
*/
sanitizeFilter?: boolean;
}
export type AnyConnectionBulkWriteModel<TSchema extends AnyObject> = Omit<mongodb.ClientInsertOneModel<TSchema>, 'namespace'>
| Omit<mongodb.ClientReplaceOneModel<TSchema>, 'namespace'>
| Omit<mongodb.ClientUpdateOneModel<TSchema>, 'namespace'>
| Omit<mongodb.ClientUpdateManyModel<TSchema>, 'namespace'>
| Omit<mongodb.ClientDeleteOneModel<TSchema>, 'namespace'>
| Omit<mongodb.ClientDeleteManyModel<TSchema>, 'namespace'>;
export type ConnectionBulkWriteModel<SchemaMap extends Record<string, AnyObject> = Record<string, AnyObject>> = {
[ModelName in keyof SchemaMap]: AnyConnectionBulkWriteModel<SchemaMap[ModelName]> & {
model: ModelName;
};
}[keyof SchemaMap];
class Connection extends events.EventEmitter implements SessionStarter {
aggregate<ResultType = unknown>(pipeline?: PipelineStage[] | null, options?: AggregateOptions): Aggregate<Array<ResultType>>;
asPromise(): Promise<this>;
base: Mongoose;
bulkWrite<TSchemaMap extends Record<string, AnyObject>>(
ops: Array<ConnectionBulkWriteModel<TSchemaMap>>,
options: mongodb.ClientBulkWriteOptions & { ordered: false }
): Promise<mongodb.ClientBulkWriteResult & { mongoose?: { validationErrors: Error[], results: Array<Error | mongodb.WriteError | null> } }>;
bulkWrite<TSchemaMap extends Record<string, AnyObject>>(
ops: Array<ConnectionBulkWriteModel<TSchemaMap>>,
options?: mongodb.ClientBulkWriteOptions
): Promise<mongodb.ClientBulkWriteResult>;
close(force?: boolean): Promise<void>;
destroy(force?: boolean): Promise<void>;
collection<T extends AnyObject = AnyObject>(name: string, options?: mongodb.CreateCollectionOptions): Collection<T>;
readonly collections: { [index: string]: Collection };
readonly config: any;
readonly db: mongodb.Db | undefined;
* Helper for `createCollection()`. Will explicitly create the given collection
* with specified options. Used to create [capped collections](https://www.mongodb.com/docs/manual/core/capped-collections/)
* and [views](https://www.mongodb.com/docs/manual/core/views/) from mongoose.
*/
createCollection<T extends AnyObject = AnyObject>(name: string, options?: mongodb.CreateCollectionOptions): Promise<mongodb.Collection<T>>;
* https://mongoosejs.com/docs/api/connection.html#Connection.prototype.createCollections()
*/
createCollections(continueOnError?: boolean): Promise<Record<string, Error | mongodb.Collection<any>>>;
* Removes the model named `name` from this connection, if it exists. You can
* use this function to clean up any models you created in your tests to
* prevent OverwriteModelErrors.
*/
deleteModel(name: string | RegExp): this;
* Helper for `dropCollection()`. Will delete the given collection, including
* all documents and indexes.
*/
dropCollection(collection: string): Promise<void>;
* Helper for `dropDatabase()`. Deletes the given database, including all
* collections, documents, and indexes.
*/
dropDatabase(): Promise<void>;
get(key: string): any;
* Returns the [MongoDB driver `MongoClient`](https://mongodb.github.io/node-mongodb-native/7.0/classes/MongoClient.html) instance
* that this connection uses to talk to MongoDB.
*/
getClient(): mongodb.MongoClient;
* The host name portion of the URI. If multiple hosts, such as a replica set,
* this will contain the first host name in the URI
*/
readonly host: string;
* A number identifier for this connection. Used for debugging when
* you have [multiple connections](/docs/connections.html#multiple_connections).
*/
readonly id: number;
* Helper for MongoDB Node driver's `listCollections()`.
* Returns an array of collection names.
*/
listCollections(): Promise<Pick<mongodb.CollectionInfo, 'name' | 'type'>[]>;
* Helper for MongoDB Node driver's `listDatabases()`.
* Returns an array of database names.
*/
listDatabases(): Promise<mongodb.ListDatabasesResult>;
* A [POJO](https://masteringjs.io/tutorials/fundamentals/pojo) containing
* a map from model names to models. Contains all models that have been
* added to this connection using [`Connection#model()`](/docs/api/connection.html#connection_Connection-model).
*/
readonly models: Readonly<{ [index: string]: Model<any> }>;
model<TSchema extends Schema = any>(
name: string,
schema?: TSchema,
collection?: string,
options?: CompileModelOptions
): Model<
InferSchemaType<TSchema>,
ObtainSchemaGeneric<TSchema, 'TQueryHelpers'>,
ObtainSchemaGeneric<TSchema, 'TInstanceMethods'>,
ObtainSchemaGeneric<TSchema, 'TVirtuals'>,
IsItRecordAndNotAny<ObtainSchemaGeneric<TSchema, 'EnforcedDocType'>> extends true
? ObtainSchemaGeneric<TSchema, 'THydratedDocumentType'>
: HydratedDocument<
InferSchemaType<TSchema>,
ObtainSchemaGeneric<TSchema, 'TVirtuals'> & ObtainSchemaGeneric<TSchema, 'TInstanceMethods'>,
ObtainSchemaGeneric<TSchema, 'TQueryHelpers'>,
ObtainSchemaGeneric<TSchema, 'TVirtuals'>,
InferSchemaType<TSchema>,
ObtainSchemaGeneric<TSchema, 'TSchemaOptions'>
>,
TSchema,
ObtainSchemaGeneric<TSchema, 'TLeanResultType'>
> & ObtainSchemaGeneric<TSchema, 'TStaticMethods'>;
model<T, U, TQueryHelpers = {}>(
name: string,
schema?: Schema<T, any, any, TQueryHelpers, any, any, any>,
collection?: string,
options?: CompileModelOptions
): U;
model<T>(name: string, schema?: Schema<T, any, any>, collection?: string, options?: CompileModelOptions): Model<T>;
modelNames(): Array<string>;
readonly name: string;
openUri(uri: string, options?: ConnectOptions): Promise<Connection>;
readonly pass: string;
* The port portion of the URI. If multiple hosts, such as a replica set,
* this will contain the port from the first host name in the URI.
*/
readonly port: number;
plugin<S extends Schema = Schema, O = AnyObject>(fn: (schema: S, opts?: any) => void, opts?: O): Connection;
plugins: Array<any>;
* Connection ready state
*
* - 0 = disconnected
* - 1 = connected
* - 2 = connecting
* - 3 = disconnecting
* - 99 = uninitialized
*/
readonly readyState: ConnectionStates;
set(key: string, value: any): any;
* Set the [MongoDB driver `MongoClient`](https://mongodb.github.io/node-mongodb-native/7.0/classes/MongoClient.html) instance
* that this connection uses to talk to MongoDB. This is useful if you already have a MongoClient instance, and want to
* reuse it.
*/
setClient(client: mongodb.MongoClient): this;
* _Requires MongoDB >= 3.6.0._ Starts a [MongoDB session](https://www.mongodb.com/docs/manual/release-notes/3.6/#client-sessions)
* for benefits like causal consistency, [retryable writes](https://www.mongodb.com/docs/manual/core/retryable-writes/),
* and [transactions](http://thecodebarbarian.com/a-node-js-perspective-on-mongodb-4-transactions.html).
*/
startSession(options?: ClientSessionOptions): Promise<ClientSession>;
* Makes the indexes in MongoDB match the indexes defined in every model's
* schema. This function will drop any indexes that are not defined in
* the model's schema except the `_id` index, and build any indexes that
* are in your schema but not in MongoDB.
*/
syncIndexes(options?: SyncIndexesOptions): Promise<ConnectionSyncIndexesResult>;
* _Requires MongoDB >= 3.6.0._ Executes the wrapped async function
* in a transaction. Mongoose will commit the transaction if the
* async function executes successfully and attempt to retry if
* there was a retryable error.
*/
transaction<ReturnType = unknown>(fn: (session: mongodb.ClientSession) => Promise<ReturnType>, options?: mongodb.TransactionOptions): Promise<ReturnType>;
useDb(name: string, options?: { useCache?: boolean }): Connection;
readonly user: string;
watch<ResultType extends mongodb.Document = any>(pipeline?: Array<any>, options?: mongodb.ChangeStreamOptions): mongodb.ChangeStream<ResultType>;
withSession<T = any>(executor: (session: ClientSession) => Promise<T>): Promise<T>;
}
export class BaseConnection extends Connection {}
}