2

I can upload files to mongodb using the standard Gridfs-stream implementation through a POST request. But, when I need to view the file metadata through GET request I'm getting error:

TypeError: Cannot read property 'files' of undefined

Apparently, it's not recognising my definition of gfs.This is my route handler:

router.get('/image/:filename', (req, res) => {

  gfs.files.find({filename: req.params.filename}, function(err, file) {
    let readStream = gfs.createReadStream({filename: file.filename});
    let data = '';
    readStream.on('data', (chunk) => {
      data += chunk.toString('base64');
    })
    readStream.on("error", function (err) {
      res.send("Image not found");
    });
    readStream.pipe(res);
  })

  res.json();
});

I have defined gridfs-stream in the simplest way:

const conn = mongoose.createConnection(URI, {useNewUrlParser:true, useUnifiedTopology:true});

let gfs;
Grid.mongo = mongoose.mongo;
conn.once('open', () => {
    gfs = Grid(conn.db);
    gfs.collection('uploads');
});

const storage = new GridFsStorage({
    url: URI,
    file: (req, file) => {...}
});

const upload = multer({ storage });

I can't understand what is the problem here, I'm stuck for days!

forest
  • 1,312
  • 3
  • 20
  • 47
  • After much hassle I found out that it is an issue with the mongodb connection using `createConnection(...)`. The connection disconnects frequently and that's when I get the error `Cannot read property 'files' of undefined`. I found no way to persist the connection for the entire duration the server is running. – forest Sep 04 '21 at 04:36

1 Answers1

0

Try using this:

app.get("/file/:filename", async (req, res) => {
    try {
        const file = await gfs.files.findOne({ filename: req.params.filename });
        const readStream = gfs.createReadStream(file.filename);
        readStream.pipe(res);
    } catch (error) {
        res.send("not found");
    }
});
Saswat
  • 180
  • 4
  • 13