首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从mongo检索文件时,this.db.collection不起作用

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

Stack Overflow用户
提问于 2019-04-19 19:25:03
回答 1查看 563关注 0票数 0

我正在尝试从mongodb地图集中检索一个文件,我使用的是gridfsstream,multer.It一直给我这个错误。

TypeError: this.db.collection不是一个函数

我可以成功上传,但检索不是working.What,我在这里失踪了吗?

代码语言:javascript
复制
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);
  });
EN

回答 1

Stack Overflow用户

发布于 2019-08-28 01:00:51

我希望还能帮助你,虽然过了几天!当我试图检索一个图像时,我也犯了同样的错误。下面是我的代码:

代码语言:javascript
复制
  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);
      })

我就这样解决了:

代码语言:javascript
复制
  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);
      })

现在对我有用了!!

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55766856

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档