Skip to content

Commit e44bd11

Browse files
committed
feat: add doucmentation on injecting a model with a named connection
1 parent 2bcdb0a commit e44bd11

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

content/techniques/mongo.md

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -253,6 +253,34 @@ To inject a given `Connection` to a custom provider (for example, factory provid
253253
}
254254
```
255255

256+
If you are just looking to inject the model from a named database, you can use the connection name as a second parameter to the `@InejctModel()` decorator.
257+
258+
```typescript
259+
@@filename(cats.service)
260+
import { Model } from 'mongoose';
261+
import { Injectable } from '@nestjs/common';
262+
import { InjectModel } from '@nestjs/mongoose';
263+
import { Cat, CatDocument } from './schemas/cat.schema';
264+
265+
@Injectable()
266+
export class CatsService {
267+
constructor(@InjectModel(Cat.name, 'cats') private catModel: Model<CatDocument>) {}
268+
}
269+
@@switch
270+
import { Model } from 'mongoose';
271+
import { Injectable, Dependencies } from '@nestjs/common';
272+
import { getModelToken } from '@nestjs/mongoose';
273+
import { Cat } from './schemas/cat.schema';
274+
275+
@Injectable()
276+
@Dependencies(getModelToken(Cat.name, 'cats'))
277+
export class CatsService {
278+
constructor(catModel) {
279+
this.catModel = catModel;
280+
}
281+
}
282+
```
283+
256284
#### Hooks (middleware)
257285

258286
Middleware (also called pre and post hooks) are functions which are passed control during execution of asynchronous functions. Middleware is specified on the schema level and is useful for writing plugins ([source](https://mongoosejs.com/docs/middleware.html)). Calling `pre()` or `post()` after compiling a model does not work in Mongoose. To register a hook **before** model registration, use the `forFeatureAsync()` method of the `MongooseModule` along with a factory provider (i.e., `useFactory`). With this technique, you can access a schema object, then use the `pre()` or `post()` method to register a hook on that schema. See example below:

0 commit comments

Comments
 (0)