Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs(connections): add note about using asPromise() with createConnection() for error handling #14364

Merged
merged 2 commits into from
Feb 22, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
18 changes: 13 additions & 5 deletions docs/connections.md
Original file line number Diff line number Diff line change
Expand Up @@ -402,16 +402,24 @@ The `mongoose.createConnection()` function takes the same arguments as
const conn = mongoose.createConnection('mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]', options);
```

This [connection](api/connection.html#connection_Connection) object is then used to
create and retrieve [models](api/model.html#model_Model). Models are
**always** scoped to a single connection.
This [connection](api/connection.html#connection_Connection) object is then used to create and retrieve [models](api/model.html#model_Model).
Models are **always** scoped to a single connection.

```javascript
const UserModel = conn.model('User', userSchema);
```

If you use multiple connections, you should make sure you export schemas,
**not** models. Exporting a model from a file is called the *export model pattern*.
The `createConnection()` function returns a connection instance, not a promise.
If you want to use `await` to make sure Mongoose successfully connects to MongoDB, use the [`asPromise()` function](https://mongoosejs.com/docs/api/connection.html#Connection.prototype.asPromise()):
vkarpov15 marked this conversation as resolved.
Show resolved Hide resolved

```javascript
// `asPromise()` returns a promise that resolves to the connection
// once the connection succeeds, or rejects if connection failed.
const conn = await mongoose.createConnection(connectionString).asPromise();
```

If you use multiple connections, you should make sure you export schemas, **not** models.
Exporting a model from a file is called the *export model pattern*.
The export model pattern is limited because you can only use one connection.

```javascript
Expand Down