MongoDB GridFs: grid.mongo.ObjectID不是构造函数



我正在使用mongoDB GridFs, node.js和express。目前我试图从数据库中获取文件,但由于某种原因,我得到这个错误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');
});
}
}

我找到了解决方案,显然有gridfs-streammongoose@5.13.12的最后一个版本的问题,我不是使用gridfs-streamgridFs.createReadStream,而是使用mongoose.mongo.GridFSBucketgridFsBucket.openDownloadStreamByName(file.filename),重构代码后看起来像这样:

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