在NestJS / Mongo中配置多个
数据库
,可以通过创建不同的MongoModule和Connection来实现。
例如,假设我们有两个
数据库
:db1和db2。我们可以创建两个不同的MongoModule,每个模块将连接到不同的
数据库
。
// mongo1.module.ts
import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { CatsSchema } from './schemas/cats.schema';
@Module({
imports: [MongooseModule.forFeature([{ name: 'Cats', schema: CatsSchema }], 'db1')],
exports: [MongooseModule],
export class MongoModule1 {}
// mongo2.module.ts
import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { DogsSchema } from './schemas/dogs.schema';
@Module({
imports: [MongooseModule.forFeature([{ name: 'Dogs', schema: DogsSchema }], 'db2')],
exports: [MongooseModule],
export class MongoModule2 {}
然后我们可以在需要使用不同数据库的模块中导入对应的MongoModule,并通过mongoose.connection.useDb()方法来指定要使用的数据库,如下所示:
import { Injectable } from '@nestjs/common';
import { InjectConnection } from '@nestjs/mongoose';
import { Connection } from 'mongoose';
import { Cat } from './interfaces/cat.interface';
@Injectable()
export class CatsService {
constructor(@InjectConnection('db1') private readonly connection: Connection) {}
async create(cat: Cat): Promise<Cat> {
const model = this.connection.model('Cats');
const createdCat = new model(cat);
return createdCat.save();
import { Injectable } from '@nestjs/common';
import { InjectConnection } from '@nestjs/mongoose';
import { Connection } from 'mongoose';
import { Dog } from './interfaces/dog.interface';
@Injectable()
export class DogsService {
constructor(@InjectConnection('db2') private readonly connection: Connection) {}
async create(dog: Dog): Promise<Dog> {
const model = this.connection.model('Dogs');
const createdDog = new model(dog);
return createdDog.save();
这样就可以成功配置多个数据库了。