Mongoose将相同的模型动态保存到多个集合中



是否可以将mongoose注入的模型保存到多个集合?(nestjs-inaction(

我在找类似的东西

injectedMode.collection('collectionA').save(data);
injectedMode.collection('collectionB').save(data);

有时我需要将模型保存到一个集合,有时又需要保存到另一个集合
请记住,模型是注入的,在我的情况下,我希望每个客户都有一个集合。因此,同一个模型需要动态保存到特定的集合

感谢

NestJS允许您访问本地Mongoose Connection,后者反过来提供对连接的db-对象的访问,因此您可以创建以下服务:

@Injectable()
export class DynamicMongoDbService {
constructor (@InjectConnection() private connection: Connection) {
}
async insert(collectionName: string, data: any) {
return this.connection.db.collection(collectionName).insert(data);
}
}

然后相应地使用此服务:

this.dynamicMongoDbService.insert('collectionA', data);
this.dynamicMongoDbService.insert('collectionB', data);

编辑:

如果模型在编译时是已知的,您还可以创建一个服务,该服务注入所有需要的模型并将它们存储在映射中。然后,在使用服务时,您可以动态地决定从哪个模型中进行选择并委托给它:

@Injectable()
export class DynamicMongoDbService {
private modelMap: Record<string, Model<any>>;
constructor (
@InjectModel(Cat.name) catModel: Model<Cat>,
@InjectModel(Dog.name) dogModel: Model<Dog>) {
this.modelMap = {
[Cat.name]: catModel,
[Dog.name]: dogModel
};
}
async insertDynamically<M, T> (modelType: typeof M, data: T) {
const model = this.modelMap[modelType.name];
return model.save(data);
}
}

这样使用:

this.dynamicMongoDbService.insert(Cat, data);
this.dynamicMongoDbService.insert(Dog, data);

最新更新