Extract file from MongoDB using GridFs - file with identifier ### is not open for writing

I save and load binary data into mongoDB database using Grid. I am using nodejs. After all the examples that I managed to find (which are very 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 identifier of the file I need. The answer I get is:

MongoError: file with id 557aa98e6f1373cb11e8f294 not opened for writing

which does not make sense because I am not writing, I am reading the file.

+4
source share
2 answers

The file does 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 used the wrong identifier.

+6
source

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

mongoose.Types.ObjectId(req.articleId)

Otherwise, MongoDB does not recognize the identifier and does not throw an error.

+1
source

All Articles