node.js - 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');
});
}
}
解决方案
我找到了解决方案,显然存在和问题gridfs-stream
的最后一个版本mongoose@5.13.12
,我不是使用gridFs.createReadStream
fromgridfs-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);
});
});
}
推荐阅读
- c# - 为什么我使用 Intrinsics API 比简单的解决方案慢?
- java - 将 PrivateKey 编码为 PKCS#1 格式,然后恢复为 PrivateKey
- android - 解决游戏商店问题;请求应用程序访问
- javascript - 数据标签错误地放置在条形图上 - chartjs
- python - 如何让我的 python 编码猜谜游戏替换已正确猜到的字母?
- java - Spring JPA在没有级联的情况下保存到存储库时获取错误分离实体传递以保持单向OneToOne关系
- javascript - fs.appendFile 不追加到新行
- javascript - 未定义的变量在 fetch api javascript 中出现,同时将其值存储在变量中
- python-3.x - python - 如何在没有熊猫的情况下在python 3中以块的形式处理(读取)大数据?
- ruby - 如何使用应在 gem 安装期间应用的捆绑配置设置环境变量?