0

i´m working with mongoDB GridFs, node.js and express. Currently im trying to get the file from the database but for some reason i get this error TypeError: grid.mongo.ObjectID is not a constructor

UploadController.ts

export default class UploadController {
  private gridFs: Grid.Grid;
  constructor() {
    autoBine(this);
    this.creatConnectionGridFs();
  }

  getImageByName(req: Request, res: Response, next: NextFunction) {
    from(this.gridFs.files.findOne({ filename: req.params.filename }))
      .pipe(
        switchMap((file) => {
          if (file) {
            return of(file);
          }
          return throwError(() => new createError.NotFound());
        })
      )
      .subscribe({
        next: (file) => {
          try {
            const readstream = this.gridFs.createReadStream(file.filename); <--- Error
            readstream.pipe(res);
          } catch (error) {
            console.log(error);
            res.json(null);
          }
        },
        error: (err) => {
          handleRouteErrors(err, res, next);
        },
      });
  }

  private creatConnectionGridFs(): void {
    const connection = mongoose.createConnection(`${process.env.MONGODB}`);
    connection.once('open', () => {
      this.gridFs = Grid(connection.db, mongoose.mongo);
      this.gridFs.collection('uploads');
    });
  }
}
Miguel Frias
  • 2,544
  • 8
  • 32
  • 53

1 Answers1

0

i found the solution, apparently there is and issue with gridfs-stream and the last version of mongoose@5.13.12, i instead of using gridFs.createReadStream from gridfs-stream i use gridFsBucket.openDownloadStreamByName(file.filename) from mongoose.mongo.GridFSBucket, after refactoring the code it looks like this:

  getImageByName(req: Request, res: Response, next: NextFunction) {
    from(this.gridFs.files.findOne({ filename: req.params.filename }))
      .pipe(
        switchMap((file) => {
          if (file) {
            return of(file);
          }
          return throwError(() => new createError.NotFound());
        })
      )
      .subscribe({
        next: (file) => {
          this.gridFsBucket.openDownloadStreamByName(file.filename).pipe(res);
        },
        error: (err) => {
          handleRouteErrors(err, res, next);
        },
      });
  }

  creatConnectionGridFs(): Promise<Grid.Grid> {
    return new Promise((resolve, reject) => {
      const connection = mongoose.createConnection(`${process.env.MONGODB}`);
      connection.once('open', () => {
        this.gridFs = Grid(connection.db, mongoose.mongo);
        this.gridFs.collection('uploads');
        this.gridFsBucket = new mongoose.mongo.GridFSBucket(connection.db, {
          bucketName: 'uploads',
        });
        resolve(this.gridFs);
      });
    });
  }
Miguel Frias
  • 2,544
  • 8
  • 32
  • 53