emiles
emiles

Reputation: 779

Download image file from MongoDB

Trying to download image file from MongoDB using route:

router.get('/:id', function(req, res) {
  gfs.findOne({ _id: mongoose.Types.ObjectId(req.params.id) }, function(err, file) {
    if (err) {
      common.handleError(err, res);
      return;
    }

    if (!file) {
      return res.json({ status: constants._ERROR, body: { message: constants._FILE_NOT_FOUND }});
    }

    res.set('Content-Type', file.contentType);
    res.set('Content-Disposition', 'attachment; filename="' + file.filename + '"');

    //console.log(file);
    var readstream = gfs.createReadStream({
      _id: file._id
    });

    readstream.on('error', function (err) {
      console.error('Read error', err);
      res.end();
    });

    readstream.pipe(res);
  });
});

Stack trace:

/Users/eric.miles/Projects/Personal/mean/emcontacts/node_modules/mongodb/lib/utils.js:123
        process.nextTick(function() { throw err; });
                                      ^

    TypeError: Cannot read property 'readPreference' of null
        at new GridStore (/Users/eric.miles/Projects/Personal/mean/emcontacts/node_modules/mongodb/lib/gridfs/grid_store.js:130:66)
        at new GridReadStream (/Users/eric.miles/Projects/Personal/mean/emcontacts/node_modules/gridfs-stream/lib/readstream.js:68:17)
        at Grid.createReadStream (/Users/eric.miles/Projects/Personal/mean/emcontacts/node_modules/gridfs-stream/lib/index.js:53:10)
        at /Users/eric.miles/Projects/Personal/mean/emcontacts/server/routes/file.js:51:26

Versions:

"gridfs-stream": "^1.1.1",
"mongoose": "^4.11.13"

Crapping out on createReadStream line. files definitely in database, "fs.files & fs.chunks".

Trying to access via Postman for now.

Upvotes: 2

Views: 1626

Answers (1)

emiles
emiles

Reputation: 779

So, what I had to do was set up my db connection like this:

mongoose.connect(mongodb_url, { useMongoClient: true });
var db = mongoose.connection;
db.options = {};
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
  console.info('database connection successful');
});

"db.options = {};" was the kicker.

Upvotes: 1

Related Questions