【问题标题】:NestJS - Mongoose with GridFSNestJS - 带有 GridFS 的猫鼬
【发布时间】:2019-01-17 11:19:16
【问题描述】:

我想在 NestJs 中使用猫鼬。我正在使用包@nestjs/mongoose,如documentation 中所述。 当我将它与标准模型一起使用时,它可以正常工作。但我需要使用GridFS 将文件存储在我的 mongo 数据库中。

如何使用此功能?是否可以与 @nestjs/mongoose 集成以使用第三方库,如 mongoose-gridfs 或其他库? 还是应该在我的NestJs 应用程序中直接使用不带@nestjs/mongoose 的猫鼬?

【问题讨论】:

    标签: node.js mongodb typescript mongoose nestjs


    【解决方案1】:

    对于那些想将猫鼬与其他需要连接的包一起使用的人,你不应该使用@nestjs/module。 这是使用标准猫鼬库的示例:https://github.com/nestjs/nest/tree/master/sample/14-mongoose-base

    【讨论】:

      【解决方案2】:

      我使用了 nestjs/mongoose 包中的 @InjectConnection() 装饰器来实现这个功能:

      export class AttachmentsService {
        private readonly attachmentGridFsRepository: any; // This is used to access the binary data in the files
        private readonly attachmentRepository: Model<AttachmentDocument>; // This is used to access file metadata
      
        constructor(@InjectConnection() private readonly mongooseConnection: Mongoose,
                    @Inject(Modules.Logger) private readonly logger: Logger) {
          this.attachmentGridFsRepository = gridfs({
            collection: 'attachments',
            model: Schemas.Attachment,
            mongooseConnection: this.mongooseConnection,
          });
      
          this.attachmentRepository = this.attachmentGridFsRepository.model;
        }
      

      我的连接是在 app.tsx 中使用 Mongoose.forRootAsync() 实例化的。

      【讨论】:

        猜你喜欢
        • 2018-08-29
        • 2019-02-13
        • 2015-11-27
        • 2019-12-20
        • 2019-08-04
        • 2021-09-18
        • 2022-06-11
        • 2021-01-05
        • 2015-06-11
        相关资源
        最近更新 更多