UNPKG

10.8 kBTypeScriptView Raw
1declare module 'mongoose' {
2 import mongodb = require('mongodb');
3 import events = require('events');
4
5 /** The Mongoose module's default connection. Equivalent to `mongoose.connections[0]`, see [`connections`](#mongoose_Mongoose-connections). */
6 const connection: Connection;
7
8 /** An array containing all connections associated with this Mongoose instance. */
9 const connections: Connection[];
10
11 /** Opens Mongoose's default connection to MongoDB, see [connections docs](https://mongoosejs.com/docs/connections.html) */
12 function connect(uri: string, options: ConnectOptions, callback: CallbackWithoutResult): void;
13 function connect(uri: string, callback: CallbackWithoutResult): void;
14 function connect(uri: string, options?: ConnectOptions): Promise<Mongoose>;
15
16 /** Creates a Connection instance. */
17 function createConnection(uri: string, options: ConnectOptions, callback: Callback<Connection>): void;
18 function createConnection(uri: string, callback: Callback<Connection>): void;
19 function createConnection(uri: string, options?: ConnectOptions): Connection;
20 function createConnection(): Connection;
21
22 function disconnect(callback: CallbackWithoutResult): void;
23 function disconnect(): Promise<void>;
24
25 /**
26 * Connection ready state
27 *
28 * - 0 = disconnected
29 * - 1 = connected
30 * - 2 = connecting
31 * - 3 = disconnecting
32 * - 99 = uninitialized
33 */
34 enum ConnectionStates {
35 disconnected = 0,
36 connected = 1,
37 connecting = 2,
38 disconnecting = 3,
39 uninitialized = 99,
40 }
41
42 /** Expose connection states for user-land */
43 const STATES: typeof ConnectionStates;
44
45 interface ConnectOptions extends mongodb.MongoClientOptions {
46 /** Set to false to [disable buffering](http://mongoosejs.com/docs/faq.html#callback_never_executes) on all models associated with this connection. */
47 bufferCommands?: boolean;
48 /** The name of the database you want to use. If not provided, Mongoose uses the database name from connection string. */
49 dbName?: string;
50 /** username for authentication, equivalent to `options.auth.user`. Maintained for backwards compatibility. */
51 user?: string;
52 /** password for authentication, equivalent to `options.auth.password`. Maintained for backwards compatibility. */
53 pass?: string;
54 /** Set to false to disable automatic index creation for all models associated with this connection. */
55 autoIndex?: boolean;
56 /** Set to `true` to make Mongoose automatically call `createCollection()` on every model created on this connection. */
57 autoCreate?: boolean;
58 }
59
60 class Connection extends events.EventEmitter implements SessionStarter {
61 /** Returns a promise that resolves when this connection successfully connects to MongoDB */
62 asPromise(): Promise<this>;
63
64 /** Closes the connection */
65 close(force: boolean, callback: CallbackWithoutResult): void;
66 close(callback: CallbackWithoutResult): void;
67 close(force?: boolean): Promise<void>;
68
69 /** Closes and destroys the connection. Connection once destroyed cannot be reopened */
70 destroy(force: boolean, callback: CallbackWithoutResult): void;
71 destroy(callback: CallbackWithoutResult): void;
72 destroy(force?: boolean): Promise<void>;
73
74 /** Retrieves a collection, creating it if not cached. */
75 collection<T extends AnyObject = AnyObject>(name: string, options?: mongodb.CreateCollectionOptions): Collection<T>;
76
77 /** A hash of the collections associated with this connection */
78 readonly collections: { [index: string]: Collection };
79
80 /** A hash of the global options that are associated with this connection */
81 readonly config: any;
82
83 /** The mongodb.Db instance, set when the connection is opened */
84 readonly db: mongodb.Db;
85
86 /**
87 * Helper for `createCollection()`. Will explicitly create the given collection
88 * with specified options. Used to create [capped collections](https://docs.mongodb.com/manual/core/capped-collections/)
89 * and [views](https://docs.mongodb.com/manual/core/views/) from mongoose.
90 */
91 createCollection<T extends AnyObject = AnyObject>(name: string, options: mongodb.CreateCollectionOptions, callback: Callback<mongodb.Collection<T>>): void;
92 createCollection<T extends AnyObject = AnyObject>(name: string, callback: Callback<mongodb.Collection<T>>): void;
93 createCollection<T extends AnyObject = AnyObject>(name: string, options?: mongodb.CreateCollectionOptions): Promise<mongodb.Collection<T>>;
94
95 /**
96 * Removes the model named `name` from this connection, if it exists. You can
97 * use this function to clean up any models you created in your tests to
98 * prevent OverwriteModelErrors.
99 */
100 deleteModel(name: string | RegExp): this;
101
102 /**
103 * Helper for `dropCollection()`. Will delete the given collection, including
104 * all documents and indexes.
105 */
106 dropCollection(collection: string, callback: CallbackWithoutResult): void;
107 dropCollection(collection: string): Promise<void>;
108
109 /**
110 * Helper for `dropDatabase()`. Deletes the given database, including all
111 * collections, documents, and indexes.
112 */
113 dropDatabase(callback: CallbackWithoutResult): void;
114 dropDatabase(): Promise<void>;
115
116 /** Gets the value of the option `key`. */
117 get(key: string): any;
118
119 /**
120 * Returns the [MongoDB driver `MongoClient`](https://mongodb.github.io/node-mongodb-native/4.9/classes/MongoClient.html) instance
121 * that this connection uses to talk to MongoDB.
122 */
123 getClient(): mongodb.MongoClient;
124
125 /**
126 * The host name portion of the URI. If multiple hosts, such as a replica set,
127 * this will contain the first host name in the URI
128 */
129 readonly host: string;
130
131 /**
132 * A number identifier for this connection. Used for debugging when
133 * you have [multiple connections](/docs/connections.html#multiple_connections).
134 */
135 readonly id: number;
136
137 /**
138 * A [POJO](https://masteringjs.io/tutorials/fundamentals/pojo) containing
139 * a map from model names to models. Contains all models that have been
140 * added to this connection using [`Connection#model()`](/docs/api/connection.html#connection_Connection-model).
141 */
142 readonly models: Readonly<{ [index: string]: Model<any> }>;
143
144 /** Defines or retrieves a model. */
145 model<TSchema extends Schema = any>(
146 name: string,
147 schema?: TSchema,
148 collection?: string,
149 options?: CompileModelOptions
150 ): Model<InferSchemaType<TSchema>, ObtainSchemaGeneric<TSchema, 'TQueryHelpers'>, ObtainSchemaGeneric<TSchema, 'TInstanceMethods'>, {}, TSchema> & ObtainSchemaGeneric<TSchema, 'TStaticMethods'>;
151 model<T, U, TQueryHelpers = {}>(
152 name: string,
153 schema?: Schema<T, any, any, TQueryHelpers, any, any>,
154 collection?: string,
155 options?: CompileModelOptions
156 ): U;
157 model<T>(name: string, schema?: Schema<T, any, any> | Schema<T & Document, any, any>, collection?: string, options?: CompileModelOptions): Model<T>;
158
159 /** Returns an array of model names created on this connection. */
160 modelNames(): Array<string>;
161
162 /** The name of the database this connection points to. */
163 readonly name: string;
164
165 /** Opens the connection with a URI using `MongoClient.connect()`. */
166 openUri(uri: string, options: ConnectOptions, callback: Callback<Connection>): Connection;
167 openUri(uri: string, callback: Callback<Connection>): Connection;
168 openUri(uri: string, options?: ConnectOptions): Promise<Connection>;
169
170 /** The password specified in the URI */
171 readonly pass: string;
172
173 /**
174 * The port portion of the URI. If multiple hosts, such as a replica set,
175 * this will contain the port from the first host name in the URI.
176 */
177 readonly port: number;
178
179 /** Declares a plugin executed on all schemas you pass to `conn.model()` */
180 plugin<S extends Schema = Schema, O = AnyObject>(fn: (schema: S, opts?: any) => void, opts?: O): Connection;
181
182 /** The plugins that will be applied to all models created on this connection. */
183 plugins: Array<any>;
184
185 /**
186 * Connection ready state
187 *
188 * - 0 = disconnected
189 * - 1 = connected
190 * - 2 = connecting
191 * - 3 = disconnecting
192 * - 99 = uninitialized
193 */
194 readonly readyState: ConnectionStates;
195
196 /** Sets the value of the option `key`. */
197 set(key: string, value: any): any;
198
199 /**
200 * Set the [MongoDB driver `MongoClient`](https://mongodb.github.io/node-mongodb-native/4.9/classes/MongoClient.html) instance
201 * that this connection uses to talk to MongoDB. This is useful if you already have a MongoClient instance, and want to
202 * reuse it.
203 */
204 setClient(client: mongodb.MongoClient): this;
205
206 /**
207 * _Requires MongoDB >= 3.6.0._ Starts a [MongoDB session](https://docs.mongodb.com/manual/release-notes/3.6/#client-sessions)
208 * for benefits like causal consistency, [retryable writes](https://docs.mongodb.com/manual/core/retryable-writes/),
209 * and [transactions](http://thecodebarbarian.com/a-node-js-perspective-on-mongodb-4-transactions.html).
210 */
211 startSession(options: ClientSessionOptions | undefined | null, callback: Callback<ClientSession>): void;
212 startSession(callback: Callback<ClientSession>): void;
213 startSession(options?: ClientSessionOptions): Promise<ClientSession>;
214
215 /**
216 * Makes the indexes in MongoDB match the indexes defined in every model's
217 * schema. This function will drop any indexes that are not defined in
218 * the model's schema except the `_id` index, and build any indexes that
219 * are in your schema but not in MongoDB.
220 */
221 syncIndexes(options: SyncIndexesOptions | undefined | null, callback: Callback<ConnectionSyncIndexesResult>): void;
222 syncIndexes(options?: SyncIndexesOptions): Promise<ConnectionSyncIndexesResult>;
223
224 /**
225 * _Requires MongoDB >= 3.6.0._ Executes the wrapped async function
226 * in a transaction. Mongoose will commit the transaction if the
227 * async function executes successfully and attempt to retry if
228 * there was a retryable error.
229 */
230 transaction(fn: (session: mongodb.ClientSession) => Promise<any>, options?: mongodb.TransactionOptions): Promise<void>;
231
232 /** Switches to a different database using the same connection pool. */
233 useDb(name: string, options?: { useCache?: boolean, noListener?: boolean }): Connection;
234
235 /** The username specified in the URI */
236 readonly user: string;
237
238 /** Watches the entire underlying database for changes. Similar to [`Model.watch()`](/docs/api/model.html#model_Model-watch). */
239 watch<ResultType extends mongodb.Document = any>(pipeline?: Array<any>, options?: mongodb.ChangeStreamOptions): mongodb.ChangeStream<ResultType>;
240 }
241
242}
243
\No newline at end of file