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

5.2k views Asked by At

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.

2

There are 2 answers

1
cauchi On BEST ANSWER

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.

0
Pablo Digiani On

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.