【问题标题】:GridFS TypeError: Cannot read property 'files' of undefinedGridFS TypeError:无法读取未定义的属性“文件”
【发布时间】:2022-01-04 08:11:27
【问题描述】:

我正在尝试从 MongoDB 上传和查看文件,但在使用 GridFS 从 MongoDB 访问文件时引发错误“TypeError: Cannot read property 'files' of undefined”。任何人,请帮助我找出这个错误。

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);
    }
    )
});

【问题讨论】:

    标签: javascript node.js mongodb web gridfs


    【解决方案1】:

    我试图找出错误。我在 app.get 函数中添加了 Grid 对象。 成功了!!

    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);
        }
        )
    });
    

    【讨论】:

      【解决方案2】:

      在该代码中,有 2 个不同的变量,名称为 gfs

      let gfs;声明的外部/全局范围内的变量,以及用var gfs = ...声明的匿名函数中的变量。

      在匿名函数内部,局部 gfs 屏蔽了全局变量,因此在该匿名函数之外设置的值不可见。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-06-03
        • 1970-01-01
        • 2016-05-12
        • 1970-01-01
        • 2020-11-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多