0

I've isolated my database connection and GridfsStorage code into its own file because I need to be able to access gridfs storage and multer upload across my application. The problem I'm facing here is that I'm unable to export the gfs variable, as shown below. I can successfully access and use the dbInstance and upload variables, just not the gfs variable, and I'm struggling to understand why that is the case.

When I try accessing gfs in my controller or in my route file, it is undefined and no methods associated with it are available.

I'm looking for a pointer to what is happening here and possible solutions. Any help is appreciated.

db.js:

const express = require('express');
const path = require('path');
const crypto = require('crypto');
const dotenv = require('dotenv');
const multer = require('multer');
const GridFsStorage = require('multer-gridfs-storage');
const Grid = require('gridfs-stream');
const mongoose = require('mongoose');

dotenv.config();

// Set up mongoose connection
const mongoDB = process.env.DB_URL;

const conn = mongoose.connect(mongoDB, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
  useCreateIndex: true,
});

mongoose.Promise = global.Promise;
const dbInstance = mongoose.connection;

let gfs;

dbInstance.once('open', () => {
  gfs = Grid(dbInstance.db, mongoose.mongo);
  gfs.collection('fileUploads');
});

const storage = new GridFsStorage({
  //url: mongoDB,
  db: dbInstance,
  file: (req, file) => {
    return new Promise((resolve, reject) => {
      crypto.randomBytes(32, (err, buff) => {
        if (err) return reject(err);
        const filename = buff.toString('hex') + path.extname(file.originalname);
        const fileInfo = {
          filename: filename,
          bucketName: 'fileUploads',
        };
        resolve(fileInfo);
      });
    });
  },
});

var upload = multer({ storage });

module.exports = {
  dbInstance,
  upload,
  gfs,
};  

1 Answer 1

0

Export an object and set a property on it. Objects are passed by reference.

So:

const gfs = {grid: undefined}

dbInstance.once('open', () => {
  gfs.grid = Grid(dbInstance.db, mongoose.mongo);
  gfs.grid.collection('fileUploads');
});

...
module.exports = {
  dbInstance,
  upload,
  gfs,
}; 

Not the answer you're looking for? Browse other questions tagged or ask your own question.