GridFS + NodeJS Extract image from mongoDB

I have the following JSON from mongoDB with images, but I don't know how to display it:


        "_id" : ObjectId("542e684a8a1cec178a172673"),
        "n" : 1,
        "data" : BinData(0,"2N6DSSfbCN/LLacNDYrJUQDEZgimMUwFpQGoJP0RU19Bi4PM82DjrUnKhE/P9v7P8ZveD1oDpFBM0iml9NE3WQmAvYFoG+nhD73Jm4N9b4LpylaAN5Ef+gVdgGSTAfSUwOikXoVick5pSQCkRmTCU5NT9VVfjHdAx74/ZhFRj+TIRjzlAhzkACBElzgMwGCo7tX+FYrpQLJ5KRmXiwFFwsNtHHzXiK1eu+CG1FumhGpA/qdG8CdDgD1xUHEcerMGO/eLGR9ML7ni/VjXxWzqp2j5DG2/WuKNv7xd3Kz/vr0MctJhuaBIl35YrKhdLnzqDa0uDa6bm4jz+eNyAI2hQbayGo4kVPFe8W7wFpY7qfBvnB9kbocxfZSdADDUNwYaydpT8lIcKEN9XfQJOYZvHp0El"),
        "files_id" : ObjectId("542e684a8a1cec178a172671")


        "_id" : ObjectId("542e65378axdeckhb0"),
        "uploadDate" : ISODate("2012-11-01"),
        "length" : 15673,
        "chunkSize" : 33222,
        "md5" : "f66e6654854a28e3672cfhds334d223b55a1"


You need to turn the "data" into a real image for display.

I am using nodeJS and I cannot find good tutorials for fetching images from mongoDB using GridFS.

Thank you for your help!


source to share

1 answer

Sorry this answer is too late, but I'm surprised no one has answered it yet. Anyway, the following code will download the file if you are using Express. You will need to wrap gfs.findOne()

in 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:
    _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);
            '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.




All Articles