【问题标题】:Mongoose save same model to mutiple collections dynamicallyMongoose 将相同的模型动态保存到多个集合中
【发布时间】:2021-01-25 03:14:49
【问题描述】:

是否可以将猫鼬注入模型保存到多个集合中? (nestjs 注入)

我正在寻找类似的东西

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

有时我需要将模型保存到一个集合中,有时又需要保存到另一个集合中。
请记住,模型是注入的,就我而言,我希望每个客户都有一个集合。所以同样的模型需要动态地保存到特定的集合中

谢谢

【问题讨论】:

    标签: mongoose nestjs


    【解决方案1】:

    NestJS 允许您访问本机 Mongoose Connection,这反过来又提供了对连接的 db-object 的访问,因此您可以创建以下服务:

    @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);
    

    【讨论】:

    • 这样做,我是否会失去注入模型的能力,以及强类型能力和 API 的所有好处,不是吗?我还能用这个模型吗?那么查询呢?谢谢!
    • 没错,也许还有别的办法——我会考虑的:)
    • 编辑了答案,你觉得这个想法怎么样?
    • 很好,但问题是我需要为每个客户收集一个集合(每个客户的那种孤立的云)。所以生病可能不得不:customerA: Model&lt;Data&gt; - 它在编译时未知...感谢您的帮助。
    猜你喜欢
    • 2013-02-13
    • 2018-10-01
    • 1970-01-01
    • 2012-10-31
    • 1970-01-01
    • 2019-06-21
    • 2017-10-08
    • 2016-12-03
    • 2018-04-24
    相关资源
    最近更新 更多