0

我处理文件的依赖项:

"dependencies": {
    "express": "^4.17.1",
    "gridfs-stream": "^1.1.1",
    "mongoose": "^5.13.0",
    "multer": "^1.4.2",
    "multer-gridfs-storage": "^5.0.0"
  },

我已经根据他们的文档和其他示例声明了 multer、gridfs-stream 和 multer-grifs-storage。我可以将图像块上传到 mongodb 但是当我GridFS用来显示文件时,我收到了错误gfs is not defined.

我的实现:

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

let gfs;

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

const storage = new GridFsStorage({
    url: mongoURI,
    file: (req, file) => {
        return new Promise((resolve, reject) => {
            crypto.randomBytes(16, (err, buf) => {
                if (err) {
                    return reject(err);
                }
                const filename = buf.toString('hex') + path.extname(file.originalname);
                const fileInfo = {
                    filename: filename,
                    bucketName: 'uploads'
                };
                resolve(fileInfo);
            });
        });
    }
});

const upload = multer({ storage });

GET然后,我对请求的路由处理程序的实现:

router.get('/:id', async (req, res) => {
  try {
    const query = await MenuItem.findById(req.params.id);
    const file = await gfs.files.find({filename: query.photo}).toArray();
    res.json(file);
  } catch (err) {
    console.error("error:", err);
    res.status(400).send(err)
  };
});

运行这条路线后,我收到了这个错误。它表示上面的调用行gfs.files.find(...)

error: TypeError: Cannot read property 'files' of undefined
    at C:\Projects\mysite\backend\routes\api\menus.js:125:28
    at processTicksAndRejections (internal/process/task_queues.js:97:5)

我该如何解决?

4

0 回答 0