GridFS + NodeJS Retrieve image from mongoDB GridFS + NodeJS Retrieve image from mongoDB mongodb mongodb

GridFS + NodeJS Retrieve image from mongoDB


Sorry this answer is super late, but I'm surprised no one has answered it yet. Anyway, the following code will download the file, presuming you are running Express. You will need to wrap the gfs.findOne() function into an API call.

const Grid = require('gridfs-stream');const mime = require('mime');const mongoose = require('mongoose');// connect to the db, fill in the username/password/host/port/dbName.// Ideally the connection is set up before the main part of the app runs.const path = 'mongodb://username:password@host:port/dbName';const dbConnection = mongoose.createConnection(path);const gfs = new Grid(dbConnection.db);// then once you get the id of the file you want:gfs.findOne({    _id: id}, (err, file) => {    if (err) {        // report the error    } else {        // detect the content type and set the appropriate response headers.        let mimeType = file.contentType;        if (!mimeType) {            mimeType = mime.lookup(file.filename);        }        res.set({            'Content-Type': mimeType,            'Content-Disposition': 'attachment; filename=' + file.filename        });        const readStream = gfs.createReadStream({            _id: id        });        readStream.on('error', err => {            // report stream error        });        // the response will be the file itself.        readStream.pipe(res);    }});