0

我已将我的数据库连接和 GridfsStorage 代码隔离到它自己的文件中,因为我需要能够访问 gridfs 存储并在我的应用程序中进行多重上传。我在这里面临的问题是我无法导出 gfs 变量,如下所示。我可以成功访问和使用 dbInstance 和上传变量,而不是 gfs 变量,我很难理解为什么会这样。

当我尝试在我的控制器或路由文件中访问 gfs 时,它是未定义的,并且没有与之关联的方法可用。

我正在寻找指向这里发生的事情和可能的解决方案的指针。任何帮助表示赞赏。

db.js:

const express = require('express');
const path = require('path');
const crypto = require('crypto');
const dotenv = require('dotenv');
const multer = require('multer');
const GridFsStorage = require('multer-gridfs-storage');
const Grid = require('gridfs-stream');
const mongoose = require('mongoose');

dotenv.config();

// Set up mongoose connection
const mongoDB = process.env.DB_URL;

const conn = mongoose.connect(mongoDB, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
  useCreateIndex: true,
});

mongoose.Promise = global.Promise;
const dbInstance = mongoose.connection;

let gfs;

dbInstance.once('open', () => {
  gfs = Grid(dbInstance.db, mongoose.mongo);
  gfs.collection('fileUploads');
});

const storage = new GridFsStorage({
  //url: mongoDB,
  db: dbInstance,
  file: (req, file) => {
    return new Promise((resolve, reject) => {
      crypto.randomBytes(32, (err, buff) => {
        if (err) return reject(err);
        const filename = buff.toString('hex') + path.extname(file.originalname);
        const fileInfo = {
          filename: filename,
          bucketName: 'fileUploads',
        };
        resolve(fileInfo);
      });
    });
  },
});

var upload = multer({ storage });

module.exports = {
  dbInstance,
  upload,
  gfs,
};  
4

1 回答 1

0

导出对象并为其设置属性。对象通过引用传递。

所以:

const gfs = {grid: undefined}

dbInstance.once('open', () => {
  gfs.grid = Grid(dbInstance.db, mongoose.mongo);
  gfs.grid.collection('fileUploads');
});

...
module.exports = {
  dbInstance,
  upload,
  gfs,
}; 
于 2020-02-18T17:18:22.890 回答