Saya juga mencari solusi untuk membaca gambar dari gridfs dan saya menggunakan grid-fs strem
ini adalah solusi yang saya temukan, semoga bermanfaat untuk Anda.
// siapkan gridfs
import mongoose from 'mongoose';
import Grid from 'gridfs-stream';
const db = mongoose.connection.db;
const mongoDriver = mongoose.mongo;
const gfs = new Grid(db, mongoDriver);
// tulis gambar ke mongo
const writeStream = gfs.createWriteStream({
filename: 'test.png',
content_type: 'image/png',
});
fs.createReadStream(filePath).pipe(writeStream);
writeStream.on('close', (gfsFile) => {
// remove the original file
fs.unlink('test.png');
// this is the information, and _id is the id
console.log(gfsFile);
});
// baca gambar ke mongo
const readstream = gfs.createReadStream({
_id: id,
});
const bufs = [];
readstream.on('data', function (chunk) {
bufs.push(chunk);
});
readstream.on('end', function () {
const fbuf = Buffer.concat(bufs);
const base64 = fbuf.toString('base64');
console.log(base64);
});