在我的Mongoose模式中,它是否可能引用另一个数据库中的集合?

lf5gs5x2  于 2023-06-23  发布在  Go
关注(0)|答案(1)|浏览(82)

我有多个数据库。第一个数据库是引用,其他数据库集合必须引用第一个数据库。
我可以使用**nestjs(mongoose)**来实现吗?如果答案是肯定的,我该怎么做?
我的 Mongoose 版本是7.1.0

mctunoxg

mctunoxg1#

在模块文件(例如,app.module.ts)中为第二个数据库创建一个连接

@Module({
  imports: [
    // Connection to the first database
    MongooseModule.forRoot('mongodb://localhost/first-database'),
    // Connection to the second database
    MongooseModule.forRoot('mongodb://localhost/second-database', {
      name: 'second-connection', // Give a name to the connection
    }),
  ],
})
export class AppModule {}

在第二个集合的架构定义中,使用 ref 属性引用第一个数据库中的集合。

@Schema({ collection: 'second-collection', _id: false, timestamps: true })
export class SecondCollection {
  @Prop({ type: Schema.Types.ObjectId, ref: 'FirstCollection', required: true })
  firstCollectionRef: string;
}

在服务控制器中使用它。

@Injectable()
export class MyService {
  constructor(
    @InjectModel(SecondCollection.name, 'second-connection')
    private readonly secondCollectionModel: Model<SecondCollection>,
  ) {}
}

有帮助!

相关问题