Skip to content

Commit 94364bc

Browse files
Merge branch 'ahmedwael216-docs/adding-mongoose-session-section'
2 parents ab77686 + c9d7e04 commit 94364bc

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

content/techniques/mongo.md

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,30 @@ export class CatsService {
193193
}
194194
```
195195

196+
#### Sessions
197+
198+
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.
199+
200+
Here's an example of how to start a session:
201+
202+
```typescript
203+
import { InjectConnection } from '@nestjs/mongoose';
204+
import { Connection } from 'mongoose';
205+
206+
@Injectable()
207+
export class CatsService {
208+
constructor(@InjectConnection() private readonly connection: Connection) {}
209+
210+
async startTransaction() {
211+
const session = await this.connection.startSession();
212+
session.startTransaction();
213+
// Your transaction logic here
214+
}
215+
}
216+
```
217+
218+
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.
219+
196220
#### Multiple databases
197221

198222
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**.

0 commit comments

Comments
 (0)