0

我正在使用gridfs和mutler将ppt pdf等文件上传到mongodb atlas。设置路由器时,它一直说找不到 db 我在配置文件中有我的 uri。我在 mongodb atlas 中缺少什么我在名为“test”的数据库中有 3 个集合我必须在集群中创建另一个 db 吗?请帮忙

if (!db) throw new Error('缺少 db 参数\nnew Grid(db, mongo)'); ^

错误:在新网格 (/Users/ezana/Desktop/Canvas/backend/node_modules/gridfs-stream/lib/index.js:25:18) 在网格 (/Users/ezana) 处缺少 db 参数新网格 (db, mongo) /Desktop/Canvas/backend/node_modules/gridfs-stream/lib/index.js:19:12)在对象。(/Users/ezana/Desktop/Canvas/backend/api/routes/fileUploadRoutes.js:9:11) 在 Object.Module._extensions 的 Module._compile (internal/modules/cjs/loader.js:701:30)。 .js (internal/modules/cjs/loader.js:712:10) 在 Module.load (internal/modules/cjs/loader.js:600:32) 在 tryModuleLoad (internal/modules/cjs/loader.js:539 :12) 在 Function.Module._load (internal/modules/cjs/loader.js:531:3) 在 Module.require (internal/modules/cjs/loader.js:637:17) 在 require (internal/modules/ cjs/helpers.js:22:18) 在对象。(/Users/ezana/Desktop/Canvas/backend/app.js:7:

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

1 回答 1

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

这对我有用。

于 2019-07-14T11:56:03.927 回答