Nest: [ Bug ] Can't use multiple providers mongoDB

Created on 13 Dec 2017  路  4Comments  路  Source: nestjs/nest

I'm submitting a...


[ ] Regression 
[x] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior


I have created 2 providers for 2 different mongo databases. But when i create a entry on the 2 different providers, will save all data on the last provider loaded.

export const databaseProviders = [
    {
        provide: 'DbApiConnectionToken',
        useFactory: async () => {
            (mongoose as any).Promise = global.Promise;
            try {
                //...
                console.log('DB API', connectionString);

                return await mongoose.connect(connectionString, {
                    useMongoClient: true,
                });
            } catch (e) {
                console.error('Error on connection mongo API DB', e);
            }

        },
    }, {
        provide: 'DbLogsConnectionToken',
        useFactory: async () => {
            (mongoose as any).Promise = global.Promise;
            try {
               ///...
                console.log('DB LOGS', connectionStringLogs);
                return await mongoose.connect(connectionStringLogs, {
                    useMongoClient: true,
                });
            } catch (e) {
                console.error('Error on connection mongo LOGS DB', e);
            }

        },
    },
];

And i have 2 modules where each module use a different provider

export const patientsProviders = [
    {
        provide: 'PatientModelToken',
        useFactory: (connection: Connection) => connection.model('Patient', PatientSchema),
        inject: ['DbApiConnectionToken'],
    },
];
export const apiLoggersProviders = [
    {
        provide: 'ApiLoggerModelToken',
        useFactory: (connection: Connection) => connection.model('Api', ApiLoggerSchema),
        inject: ['DbLogsConnectionToken'],
    },
];

On the workflow the first service called is it:

@Component()
export class ApiLoggerService {
    constructor(@Inject('ApiLoggerModelToken') private readonly apiLoggerModel: Model<ApiLogger>) {

    }

    async createAsync(create: CreateApiLoggerDto): Promise<ApiLogger> {
        const created = new this.apiLoggerModel(create);
        return await created.save();
    }

}

So, it's good, this model save the data on good database. And after this service is called a new service is also called which should save the date on the other database. Because the PatientModelToken is associated to provider DbApiConnectionToken but is stored on DbLogsConnectionToken

@Component()
export class PatientsService extends RestService<Patient> {
    constructor(@Inject('PatientModelToken') private readonly patientModel: Model<Patient>) {
        super(patientModel);
    }

Environment

Nest version: 4.4.0

Most helpful comment

Hi @cojack , thanks you that work's.

It's simply change the connection system to mongo. Change the connect to createConnection like this .

export const databaseProviders = [
    {
        provide: 'DbApiConnectionToken',
        useFactory: async () => {
            (mongoose as any).Promise = global.Promise;
            try {
                //...
                console.log('DB API', connectionString);

                return await mongoose.createConnection(connectionString, {
                    useMongoClient: true,
                });
            } catch (e) {
                console.error('Error on connection mongo API DB', e);
            }

        },
    }, {
        provide: 'DbLogsConnectionToken',
        useFactory: async () => {
            (mongoose as any).Promise = global.Promise;
            try {
               ///...
                console.log('DB LOGS', connectionStringLogs);
                return await mongoose.createConnection(connectionStringLogs, {
                    useMongoClient: true,
                });
            } catch (e) {
                console.error('Error on connection mongo LOGS DB', e);
            }

        },
    },
];

All 4 comments

@workfel it's not related to nest at all, please read the docs of mongoose more carefully: http://mongoosejs.com/docs/connections.html#multiple_connections

Hi @cojack , thanks you that work's.

It's simply change the connection system to mongo. Change the connect to createConnection like this .

export const databaseProviders = [
    {
        provide: 'DbApiConnectionToken',
        useFactory: async () => {
            (mongoose as any).Promise = global.Promise;
            try {
                //...
                console.log('DB API', connectionString);

                return await mongoose.createConnection(connectionString, {
                    useMongoClient: true,
                });
            } catch (e) {
                console.error('Error on connection mongo API DB', e);
            }

        },
    }, {
        provide: 'DbLogsConnectionToken',
        useFactory: async () => {
            (mongoose as any).Promise = global.Promise;
            try {
               ///...
                console.log('DB LOGS', connectionStringLogs);
                return await mongoose.createConnection(connectionStringLogs, {
                    useMongoClient: true,
                });
            } catch (e) {
                console.error('Error on connection mongo LOGS DB', e);
            }

        },
    },
];

@workfel you're welcome :smile_cat:

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

Was this page helpful?
0 / 5 - 0 ratings