从mongo检索文件时this.db.collection不起作用

时间:2019-04-19 19:25:03

标签: node.js express mongoose

我正在尝试使用gridfsstream和multer从mongodb atlas检索文件。它一直给我这个错误。

  

TypeError:this.db.collection不是函数

我可以成功上传,但无法正常工作。我在这里缺少什么

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

// set up connection to db for file storage
const storage = require("multer-gridfs-storage")({
  url: config,
  file: (req, file) => {
    return {
      filename: file.originalname
    };
  }
});
// sets file input to single file
const singleUpload = multer({ storage: storage }).single("file");



  router.get("/files", (req, res) => {
  gfs.files.find().toArray((err, files) => {
    if (!files || files.length === 0) {
      return res.status(404).json({
        message: "Could not find files"
      });
    }
    return res.json(files);
  });

1 个答案:

答案 0 :(得分:0)

尽管已经过去了一段时间,但我希望仍然能为您提供帮助!尝试检索图像时出现相同的错误。下面是我的代码:

  MongoClient.connect(config.Info.mongo_database, {}, (err, client) => {
        if(err) { new Error("An error has occurred while this file is retrieving: "+ err); }

        //throw the error: this.db.collection is not a function
        let bucket = new mongo.GridFSBucket(client.db,  {
          bucketName: bucketName
        });

        bucket.openDownloadStreamByName(filename).pipe(response);
      })

我这样解决:

  MongoClient.connect(config.Info.mongo_database, {}, (err, client) => {
        if(err) { new Error("An error has occurred while this file is retrieving: "+ err); }

        //Look this, I must to explicit database name, otherwise that error is thrown
        let db = client.db('files_repository');

        let bucket = new mongo.GridFSBucket(db,  {
          bucketName: bucketName
        });

        bucket.openDownloadStreamByName(filename).pipe(response);
      })

现在对我有用!