Skip to content

Commit

Permalink
chore: improve wording
Browse files Browse the repository at this point in the history
  • Loading branch information
kamilmysliwiec committed Oct 17, 2024
1 parent 2396348 commit c9d7e04
Showing 1 changed file with 19 additions and 4 deletions.
23 changes: 19 additions & 4 deletions content/techniques/mongo.md
Original file line number Diff line number Diff line change
Expand Up @@ -193,15 +193,30 @@ export class CatsService {
}
```

### Sessions
To start a session with mongoose you shouldn't use `mongoose.startSession()` directly. Instead inject the connection using [@InjectConnection](http://localhost:4200/techniques/mongodb#connection), then use the connection object to start the session.
#### Sessions

To start a session with Mongoose, it's recommended to inject the database connection using `@InjectConnection` rather than calling `mongoose.startSession()` directly. This approach allows better integration with the NestJS dependency injection system, ensuring proper connection management.

Here's an example of how to start a session:

```typescript
const session = await this.connection.startSession();
session.startTransaction();
import { InjectConnection } from '@nestjs/mongoose';
import { Connection } from 'mongoose';

@Injectable()
export class CatsService {
constructor(@InjectConnection() private readonly connection: Connection) {}

async startTransaction() {
const session = await this.connection.startSession();
session.startTransaction();
// Your transaction logic here
}
}
```

In this example, `@InjectConnection()` is used to inject the Mongoose connection into the service. Once the connection is injected, you can use `connection.startSession()` to begin a new session. This session can be used to manage database transactions, ensuring atomic operations across multiple queries. After starting the session, remember to commit or abort the transaction based on your logic.

#### Multiple databases

Some projects require multiple database connections. This can also be achieved with this module. To work with multiple connections, first create the connections. In this case, connection naming becomes **mandatory**.
Expand Down

0 comments on commit c9d7e04

Please sign in to comment.