Working on a project with Nestjs 6.x, Mongoose, Mongo, etc... Regarding to the Back End, in my use case, I must change the connection of one of my databases depending of some conditions/parameters coming from some requests.
Basically, I have this
mongoose.createConnection('mongodb://127.0.0.1/whatever-a', { useNewUrlParser: true })
and I want to change to, for example
mongoose.createConnection('mongodb://127.0.0.1/whatever-b', { useNewUrlParser: true })
Therefore, I have in Nestjs the first provider
export const databaseProviders = [
{
provide: 'DbConnectionToken',
useFactory: async (): Promise<typeof mongoose> =>
await mongoose.createConnection('mongodb://127.0.0.1/whatever', { useNewUrlParser: true })
}
I was researching for a while and I found out that in release Nestjs 6.x there are provider requests allowing me to modify dynamically Per-request the injection of some providers.
Anyway, I don't know how to achieve my change neither if it is going to be working in case I'd achieve that
Can anyone help or guide me? Many thanks in advance.
2条答案
按热度按时间bjp0bcyl1#
You can do the following using Nest's built-in Mongoose package:
Then, you can attach whatever you want to the request and change the database per request; hence the use of the
Scope.REQUEST
. You can read more about Injection Scopes on their docs.Edit: If you run into issues with PassportJS (or any other package) or the request is empty, it seems to be an error that relates to PassportJS (or the other package) not supporting request scopes; you may read more about the issue on GitHub regarding PassportJS .
dldeef672#
我为nest-mongodb做了一个简单实现,
主要的变化是在mongo-core.module.ts中,我将连接存储在一个Map中,如果可用的话就使用它们,而不是每次都创建一个新的连接。
查看完整的implementation