nestjs / mongoose

Mongoose module for Nest framework (node.js) 🍸
https://nestjs.com
MIT License
528 stars 118 forks source link

Allow to specify connection for @InjectModel() decorator #1014

Closed Ginden closed 3 years ago

Ginden commented 3 years ago

I'm submitting a...

Current behavior

Currently, you can't inject the same model for two different connections.

Expected behavior

Minimal reproduction of the problem with instructions

@Injectable()
export class FooService {
   constructor(
       @InjectModel(User.name) private userModel: Model<User>,
       @InjectModel(User.name) private readonlyUserModel: Model<User>
       ) {} 
}

@Module({
  imports: [MongooseModule.forFeatureAsync(..., DEFAULT_DB_CONNECTION), MongooseModule.forFeatureAsync(..., READONLY_DB_CONNECTION)]
  providers: [FooService]
})
export class FooModule {}

What is the motivation / use case for changing the behavior?

This is important for read scaling Mongo databases if you use multi-document transactions. Reads in transaction have to read from primary node, but other workloads can read from secondary nodes.

Therefore, workarounds are required for inject two models (eg. reexporting Model<User> from another module with custom provider token).

Another use case is security - limiting user privileges limits potential impact of query injection.

Environment

Newest versions of everything.

kamilmysliwiec commented 3 years ago

Let's track this here https://github.com/nestjs/mongoose/pull/1023