我正在使用 grid-stream 和 girdFsStorage 库从 mongodb 获取图像。
我将图像上传到 db 没问题,但是当我尝试从 db 获取图像时失败。
我预计 db.collection 会返回,gfs.files.findOne({ filename: req.params.filename }, (err, file) => {...}
但 this.db.collection 会返回。有任何想法吗?
TypeError:this.db.collection 不是函数
这是我的数据库连接
let db = mongoose.connect(init.mongoUrl)
.then(() => console.log('Connected to MongoDB...'))
.catch(err => console.error(('Could not connect to MongoDB...\n'), err))
这是我从数据库获取图像的代码
// Init stream
const gfs = Grid(db, mongoose.mongo);
api.get('/image/:filename', (req, res) => {
gfs.files.findOne({ filename: req.params.filename }, (err, file) => {
// Check if file
if (!file || file.length === 0) {
return res.status(404).json({
err: 'No file exists'
});
}
// Check if image
if (file.contentType === 'image/jpeg' || file.contentType === 'image/png') {
// Read output to browser
const readstream = gfs.createReadStream(file.filename);
readstream.pipe(res);
} else {
res.status(404).json({
err: 'Not an image'
});
}
});
});