node.jsmongodbnestjsgridfsmulter-gridfs-storage

How to integrate Mongoose and GridFS to NestJS?


Whats is the correct way to work with Mongoose and GridFS?

I'm trying to add Mongodb Gridfs to NestJS Example 14 (https://github.com/nestjs/nest/tree/master/sample/14-mongoose-base)

But when I use the tag @InjectConnection:

  // files.service.ts
  private readonly fileModel: MongoGridFS;
  constructor(@InjectConnection() private readonly connection: Connection) {
    this.fileModel = new MongoGridFS(this.connection.db, 'fs');
  }
  async readStream(id: string): Promise<GridFSBucketReadStream> {
    return await this.fileModel.readFileStream(id);
  }

The following error occurs:

[Nest] 24282   - 04/20/2020, 4:10:23 PM   [ExceptionHandler] Nest can't resolve dependencies of the FilesService (?). Please make sure that the argument DatabaseConnection at index [0] is available in the FilesModule context.

Potential solutions:
- If DatabaseConnection is a provider, is it part of the current FilesModule?
- If DatabaseConnection is exported from a separate @Module, is that module imported within FilesModule?
  @Module({
    imports: [ /* the Module containing DatabaseConnection */ ]
  })

Error: Nest can't resolve dependencies of the FilesService (?). Please make sure that the argument DatabaseConnection at index [0] is available in the FilesModule context.

Solution

  • As the MongooseModule is not @Global(), you'll need to import the module wherever you need a database connection. In your example, you only have the MulterModule being imported, so when you try to do @InjectConnection(), Nest cannot find the MongooseModule where the Connection comes from, and thus throws an error. Import the MongooseModule to fix this.