Skip to content

Commit 952cf7b

Browse files
Merge pull request #2434 from jmcdo29/feat/mention-connection-name-mongo
feat: add doucmentation on injecting a model with a named connection
2 parents 2bcdb0a + 8168379 commit 952cf7b

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

content/techniques/mongo.md

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -253,6 +253,24 @@ 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 `@InjectModel()` decorator.
257+
258+
```typescript
259+
@@filename(cats.service)
260+
@Injectable()
261+
export class CatsService {
262+
constructor(@InjectModel(Cat.name, 'cats') private catModel: Model<CatDocument>) {}
263+
}
264+
@@switch
265+
@Injectable()
266+
@Dependencies(getModelToken(Cat.name, 'cats'))
267+
export class CatsService {
268+
constructor(catModel) {
269+
this.catModel = catModel;
270+
}
271+
}
272+
```
273+
256274
#### Hooks (middleware)
257275

258276
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)