0

I am getting a error "Cannot read properties of undefined (reading 'files')" I want to be able to upload a video into my media bucket, but when clicking its link to stream the uploaded video I get the following error

[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node index.js`
Server is running on : http://localhost:8000
MongoDB is connected!
TypeError: Cannot read properties of undefined (reading 'files')
unable to fetch files

I notice that the "files" in const files =await gfs.files.find().toArray() is not highlighted and I think there is a issue with this line. I am just not sure what exactly.

Sometimes the video links will show up and I am able to delete them, but when I click on them all I receive is a "{}" in the route

server.js:

app.get('/files',async(req,res)=>{
try{
  const files =await gfs.files.find().toArray()

  res.json(files)

}catch(err){
  console.log(err)
  console.log("unable to fetch file")
  res.status(400).send(err)
}

app.js

  const fetchFiles = React.useCallback(async () => {
    const res = await axios.get("http://localhost:8000/files");
    setFiles(res.data);
  }, []);

gfs is defined here

let gfs;
//mongoose.Promise = global.Promise;
const conn = mongoose.connection
// create a stream connection with our cluster
conn.once('open', async() => {
  //Init Stream
  gridfsBucket = new mongoose.mongo.GridFSBucket(conn.db, {
    bucketName: 'media'
  })
  gfs = await Grid(conn.db, mongoose.mongo);
  gfs.collection('media');
})

jayshinobi
  • 21
  • 3
  • `gfs.files` is undefined. What is `gfs` and where is it defined? – evolutionxbox Jul 05 '22 at 14:49
  • I have added the code above and it is defined in my server.js. gfs = await Grid(conn.db, mongoose.mongo); – jayshinobi Jul 05 '22 at 15:17
  • It seems like you need to put the `app.get` inside of the `conn.once` callback – evolutionxbox Jul 05 '22 at 15:45
  • i am not exactly sure what you mean by that I have other routes that use gfs like my delete route. wouldn't that cause more issues? Maybe I'm not understanding. – jayshinobi Jul 05 '22 at 17:39
  • Does this answer your question? [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – evolutionxbox Jul 05 '22 at 22:47

0 Answers0