Read file from GridFS based on _ID using mongoskin & nodejs

185 views Asked by At

I am using mongoskin in my nodejs based application. I have used GridFS to uplaod the file. I am able to upload and read it back using the "filename" however I want to read it back using _id. How can i do? Following are code details.

Working code to read the file based on filename:

exports.previewFile = function (req, res) {
    var contentId = req.params.contentid;
    var gs = DBModule.db.gridStore('69316_103528209714703_155822_n.jpg', 'r');
    gs.read(function (err, data) {
        if (!err) {
            res.setHeader('Content-Type', gs.contentType);
            res.end(data);
        } else {
            log.error({err: err}, 'Failed to read the content for id '+contentId);
            res.status(constants.HTTP_CODE_INTERNAL_SERVER_ERROR);
            res.json({error: err});
        }
    });
};

How this code can be modified to make it work based on id?

1

There are 1 answers

0
joy On

After few hit & trial following code works. This is surprise bcz input parameter seems searching on all the fields.

//view file from database
exports.previewContent = function (req, res) {
    var contentId = new DBModule.BSON.ObjectID(req.params.contentid);
    console.log('Calling previewFile inside FileUploadService for content id ' + contentId);

    var gs = DBModule.db.gridStore(contentId, 'r');
    gs.read(function (err, data) {
        if (!err) {
            //res.setHeader('Content-Type', metadata.contentType);
            res.end(data);
        } else {
            log.error({err: err}, 'Failed to read the content for id ' + contentId);
            res.status(constants.HTTP_CODE_INTERNAL_SERVER_ERROR);
            res.json({error: err});
        }
    });
};