连接gridfs multer和mongodb时缺少db参数错误

时间:2019-04-15 20:25:32

标签: express mongoose gridfs mongodb-atlas multer-gridfs-storage

我正在使用gridfs和mutler将诸如ppt pdf等文件上传到mongodb地图集。当设置路由器时,它总是说找不到db,我在配置文件中没有我的uri。我在mongodb Atlas中缺少什么?我在名为'test'的数据库中有3个集合,我是否必须在集群中创建另一个db?请帮助

  
    

如果(!db)抛出新错误('缺少db参数\ nnew Grid(db,mongo)');                ^

  
     

错误:缺少db参数new Grid(db,mongo)       在新的网格(/Users/ezana/Desktop/Canvas/backend/node_modules/gridfs-stream/lib/index.js:25:18)       在网格(/Users/ezana/Desktop/Canvas/backend/node_modules/gridfs-stream/lib/index.js:19:12)       在对象。 (/Users/ezana/Desktop/Canvas/backend/api/routes/fileUploadRoutes.js:9:11)       在Module._compile(内部/模块/cjs/loader.js:701:30)       在Object.Module._extensions..js(内部/模块/cjs/loader.js:712:10)       在Module.load(internal / modules / cjs / loader.js:600:32)       在tryModuleLoad(内部/模块/cjs/loader.js:539:12)       在Function.Module._load(内部/模块/cjs/loader.js:531:3)       在Module.require(internal / modules / cjs / loader.js:637:17)       在要求时(内部/模块/cjs/helpers.js:22:18)       在对象。 (/用户/ ezana /桌面/画布/后端/app.js:7:21)       在Module._compile(内部/模块/cjs/loader.js:701:30)       在Object.Module._extensions..js(内部/模块/cjs/loader.js:712:10)       在Module.load(internal / modules / cjs / loader.js:600:32)       在tryModuleLoad(内部/模块/cjs/loader.js:539:12)       在Function.Module._load(internal / modules / cjs / loader.js:531:3)

const router = require('express').Router();
const multer = require('multer');
const db = require('./config/main').mongoURI;
const {
    mongo,
    connection
} = require('mongoose');
const Grid = require('gridfs-stream');
Grid.mongo = mongo;
const gfs = Grid(connection.db);

const storage = require('multer-gridfs-storage')({
    db: connection.db,
    file: (req, file) => {
        return {
            filename: file.originalname
        }
    }
});

1 个答案:

答案 0 :(得分:0)

const mongoose = require("mongoose");
const multer = require("multer");
const Grid = require("gridfs-stream");
const GridFsStorage = require("multer-gridfs-storage");
const db = mongoose.connection;

let gfs;
db.once("open", function() {
  gfs = Grid(db.db, mongoose.mongo);
});



const storage = new GridFsStorage({
  url:
    url,
  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);
      });
    });
  }
});

这对我有用。