DEV Community

Discussion on: Uploading Files to MongoDB with GridFS and Multer Using NodeJS

Collapse
 
phillipdacosta profile image
Phillip DaCosta • Edited

Hello! Thank you for this helpful post! I have an issue I need some help with though.
I was able to successfully upload the images into MongoDB. However, I am not having much success retrieving the images and sending it to the frontend. The error I am currently getting is TypeError: Cannot read property 'find' of undefined ..this is happening at my ' gfs.find().toArray((err, files) => ' line under my 'app.get('/profilePicture' )' request. ..

`
const express = require('express')
const path = require('path')
const crypto = require('crypto')//to generate file name
const mongoose = require('mongoose')
const multer = require('multer')
const GridFsStorage = require('multer-gridfs-storage')
const Grid = require('gridfs-stream')
const app = express()

//CORS Middleware
app.use(function (req, res, next) {
//Enabling CORS
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,HEAD,OPTIONS,POST,PUT');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, x-client-key, x-client-token, x-client-secret, Authorization');
next();
});

const uri = "mongodb+srv://fakeaccount:password@xxxxx.mongodb.net/x_app?retryWrites=lkngdndfg"

let conn = mongoose.connection
var gfs
conn.once('open', () => {
//initialize our stream
gfs = Grid(conn.db, mongoose.mongo)
gfs.collection('employee')
})

let storage = new GridFsStorage({
url: uri,
file: (req, file) => {
return new Promise(
(resolve, reject) => {
const fileInfo = {
filename: file.originalname,
bucketName: "imageUpload"
}
resolve(fileInfo)

        })  }
Enter fullscreen mode Exit fullscreen mode

})

const upload = multer({ storage })

app.post("/uploadImg",upload.single("profilePic"),(req,res)=>{

console.log(req.body)
Enter fullscreen mode Exit fullscreen mode

res.json({file:req.file})
})

app.get('/proficPicture', (req, res) => {

    gfs.find().toArray((err, files) => {
        //check if files exist
        if (!files || files.length == 0) {
            return res.status(404).json({
                err: "No files exist"
            }) }
        // files exist
        return res.json(files)
    })


})

const PORT =5000
app.listen(PORT,()=>console.log(`Server started on port ${PORT}`))
Enter fullscreen mode Exit fullscreen mode