Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract file from MongoDB using GridFs - file with id ### not opened for writing

I'm saving and loading binary data to a mongoDB database using Grid. I'm using nodejs. Following all the examples I've been able to found (which are pretty similar) my code is:

router.get('/getlog',function(req,res) {
    if (req.isAuthenticated())
    {
        var mongo = require('mongodb');
        var Grid = require('gridfs-stream');
        var db = new mongo.Db('logApp', new mongo.Server("127.0.0.1", 27017));

        db.open(function (err) {
            if (err) {
                return handleError(err);
            }

            var gfs = Grid(db, mongo);

            var readStream = gfs.createReadStream({
                _id: req.query.id
            }).pipe(res);
        });        
    }
    else
        res.redirect('/home');
});

req.query.id is the id of the file I need. The response I get is:

MongoError: file with id 557aa98e6f1373cb11e8f294 not opened for writing

which makes no sense because I'm not writing, I'm reading the file.

like image 591
cauchi Avatar asked Dec 19 '22 03:12

cauchi


2 Answers

The file did not exist. I checked using:

 gfs.exist({_id: req.query.id+''}, function (err, found) {
  if (err) return handleError(err);
  found ? console.log('File exists') : console.log('File does not exist');
  res.send(found)
});

I was using the wrong id.

like image 130
cauchi Avatar answered Dec 21 '22 17:12

cauchi


If someone is using Mongoose, make sure you wrap the string id with:

mongoose.Types.ObjectId(req.articleId)

Otherwise MongoDB will not recognize the id and will throw an error.

like image 42
Pablo Digiani Avatar answered Dec 21 '22 17:12

Pablo Digiani