Home > Blockchain >  GridFS TypeError: Cannot read property 'files' of undefined
GridFS TypeError: Cannot read property 'files' of undefined

Time:01-04

I'm trying to upload and view files from MongoDB but while accessing files from MongoDB using GridFS raising an error "TypeError: Cannot read property 'files' of undefined". Anyone, please help me to figure out this error.

let gfs;
conn.once('open', function () {
    var gfs = Grid(conn.db, mongoose.mongo);
    gfs.collection('uploads');
});
app.get('/files',(req,res)=>{
    gfs.files.find().toArray((err,files)=>{
        if (err) return res.status(400).json({err});
        return res.json(files);
    }
    )
});

CodePudding user response:

I tried to figure out the error. I added the Grid object inside the app.get function. It worked!!

app.get('/files',(req,res)=>{
    var gfs = Grid(conn.db, mongoose.mongo);
    gfs.collection('uploads');
    gfs.files.find().toArray((err,files)=>{
        if (err) return res.status(400).json({err});
        return res.json(files);
    }
    )
});

CodePudding user response:

In that code there are 2 distinct variables with the name gfs.

The variable in the outer/global scope declared with let gfs;, and the variable in the anonymous function declared with var gfs = ....

Inside the anonymous function, the local gfs masks the global variable, so the value set there is not visible outside of that anonymous function.

  •  Tags:  
  • Related