4

我收到以下错误。基本配置如下:我已经在服务器上上传了文件,我想下载它们,但是收到这些错误我调用了一个 POST 请求到 /api/files/delete/${fileId} 应该调用路由并返回文件到浏览器,而不是使用 Grid 相关模块获取错误。

MONGODB_CONNECTION_STRING = mongodb://localhost:27017/Cstore

Db structure={Cstore:{uploads.files,uploads.chunks,users}}

On requesting POST         axios.post(`/api/files/delete/${fileId}`)

Getting error: 

     this._store = new grid.mongo.GridStore(grid.db, this.id || new grid.mongo.ObjectID(), this.name, this.mode, options);
[0]                 ^
[0] 
[0] TypeError: grid.mongo.GridStore is not a constructor
[0]     at new GridReadStream (/home/lenovo/Desktop/react/cstore/node_modules/gridfs-stream/lib/readstream.js:68:17)

This is server.js

      app.get('/image/:filename', (req, res) => {
    gfs.files.findOne({ 
      _id: mongoose.Types.ObjectId(req.params.filename)
      // filename: req.params.filename.toString()
    }, (err, file) => {
      // Check if file
      if (!file || file.length === 0) {
        console.log("not found")
        return res.status(404).json({
          
          err: 'No file exists'
        });
      }

      // Check if image
      if (file.contentType === 'image/jpeg' || file.contentType === 'image/png') {
        // Read output to browser
        console.log(file)
        let id=file._id;

        const readStream = gfs.createReadStream(
          {
            _id: mongoose.Types.ObjectId(req.params.filename)
          }
          // {
          // _id: id
          // }
        )
        readStream.on('error', err => {
            // report stream error
            console.log(err);
        });
        // the response will be the file itself.
        readStream.pipe(res);

      //   let readstream = gfs.createReadStream(mongoose.Types.ObjectId(file._id))
      //   readstream.pipe(res)
      // } else {
        res.status(404).json({
          err: 'Not an image'
        });
      }
    });
  });



  

    mongoose.Promise = global.Promise;
      mongoose.connect(
        mongoURI,
        {
          useNewUrlParser: true,
          useUnifiedTopology: true,
        },
        (err) => {
          if (err) throw err;
          console.log('MongoDB connection established');
        }
      )
      const connection = mongoose.connection;
    
      ///  HANDLING FILE
      let gfs;
      connection.once('open', () => {
        // Init stream
        gfs = Grid(connection.db, mongoose.mongo);
        gfs.collection('uploads');
      });
    
      const storage = new GridFsStorage({
        url: mongoURI, 
        file: (req, file) => {
          return new Promise((resolve, reject) => {
            crypto.randomBytes(16, (err, buf) => {
              if (err) {
                return reject(err);
              }
              const filename = file.originalname;
              const fileInfo = {
                filename: filename,
                bucketName: 'uploads'
              };
              resolve(fileInfo);
            });
          });
        }
      })
    
      const upload = multer({ storage });

Initial:
  const express = require('express');
  const mongoose = require('mongoose');
  const cookieParser = require('cookie-parser');
  const path = require('path');

  const multer = require('multer');
  const {GridFsStorage} = require('multer-gridfs-storage');
  const Grid = require('gridfs-stream');
  const methodOverride = require('method-override')
  const crypto = require('crypto')

  const app = express();

  app.use(express.json());
  app.use(express.urlencoded({ extended: true }));
  app.use(methodOverride('_method'));
  app.use(cookieParser());

  const dotenv=require('dotenv');
  dotenv.config({path:__dirname+'/.env'});

  const mongoURI = process.env.MONGODB_CONNECTION_STRING
4

2 回答 2

3

我也遇到过类似的问题。我的解决方案是猫鼬版本。该问题出现在 6.0.5 版本中,但在 5.13.7 版本中有效

于 2021-09-07T04:57:54.117 回答
3

GridStore 已弃用。您可以使用 GridFSBucket 实例对存储桶中的文件调用读写操作。文件

 let gfs, gridfsBucket;
  conn.once('open', () => {
   gridfsBucket = new mongoose.mongo.GridFSBucket(conn.db, {
   bucketName: 'your_bucket_name'
 });

   gfs = Grid(conn.db, mongoose.mongo);
   gfs.collection('your_bucket_name');
})

if(file.contentType === 'image/jpeg' || file.contentType 
 ==='image/png') 
 {
    const readStream = gridfsBucket.openDownloadStream(file._id);
    readStream.pipe(res);
 }
于 2022-01-12T10:51:47.360 回答