【问题标题】: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
【解决方案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() 实例化的。