首页 > 解决方案 > MongoDB GridFs:grid.mongo.ObjectID 不是构造函数

问题描述

我正在使用 mongoDB GridFs、node.js 和 express。目前我试图从数据库中获取文件,但由于某种原因我得到了这个错误TypeError: grid.mongo.ObjectID is not a constructor

上传控制器.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');
    });
  }
}

标签: node.jsmongodbexpressgridfs-stream

解决方案


我找到了解决方案,显然存在和问题gridfs-stream的最后一个版本mongoose@5.13.12,我不是使用gridFs.createReadStreamfromgridfs-stream我使用gridFsBucket.openDownloadStreamByName(file.filename)from mongoose.mongo.GridFSBucket,在重构代码后它看起来像这样:

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

推荐阅读