UNPKG

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