【问题标题】:how to replace gridStore to gridFSBucket?如何将 gridStore 替换为 gridFSBucket?
【发布时间】:2020-04-30 04:43:42
【问题描述】:

我有这个错误信息:

(node:11976) DeprecationWarning: GridStore is deprecated, and will be removed in a future version. Please use GridFSBucket instead

有时我无法查看图片,我猜是因为文档不佳,我不知道如何将代码切换到 GridFSBucket,就是这样:

conn.once("open", () => {
  // Init stream
  gfs = Grid(conn.db, mongoose.mongo);
  //gfs = new mongoose.mongo.GridFSBucket(conn.db);
  gfs.collection("user_images");
});


var storageImage = new GridFsStorage({
  url: dbURI,
  options: { useNewUrlParser: true, useUnifiedTopology: true },
  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: "user_images"
        };
        resolve(fileInfo);
      });
    });
  }
});
const uploadImage = multer({ storage: storageImage });

    const uploadImage = multer({ storage: storageImage });
router.get("/image/:filename", (req, res) => {
  gfs.files.findOne({ filename: req.params.filename }, (err, file) => {
    if (!file || file.length === 0) {
      return res.status(404).json({
        err: "No file exists"
      });
    }

    if (file.contentType === "image/jpeg" || file.contentType === "image/png") {
      const readstream = gfs.createReadStream(file.filename);
      //const readstream = gridFSBucket.openUploadStream(file.filename);
      readstream.pipe(res);
    } else {
      res.status(404).json({
        err: "Not an image"
      });
    }
  });
});

非常感谢您的帮助,我需要在此处进行哪些更改才能使其与 GridFsBucket 一起使用,提前非常感谢!

【问题讨论】:

  • "..查看图片时出现问题.." 你的意思是用 html 格式预览吗?还是之后下载会导致错误?

标签: node.js gridfs gridfs-stream


【解决方案1】:

聚会迟到了,但由于我偶然发现了同样的问题,而现有的答案并不能解决问题,我会继续发布我发现的内容,以防其他人偶然发现同样的问题未来:

// Old Way:
const conn = mongoose.createConnection(youConnectionURI);
const gfs = require('gridfs-store')(conn.db);
gfs.collection('yourBucketName');

// New Way:
const conn = mongoose.createConnection(youConnectionURI);
const gridFSBucket = new mongoose.mongo.GridFSBucket(conn.db, {bucketName: 'yourBucketName'});

有关如何使用 GridFSBucket 执行 CRUD 操作 的更多信息,请查看 this pagethis page

【讨论】:

    【解决方案2】:

    我最终遇到了同样的问题,您很可能确定 readstream = gfs.createReadStream(file.filename);是导致错误的原因。只需添加一个新变量并更改一行即可。

    //add var
    let gridFSBucket;
    let gfs;
    connection.once('open', () => {
      gfs = Grid(conn.db, mongoose.mongo);
      // add value to new var
      gridFSBucket = new mongoose.mongo.GridFSBucket(conn.db, {
        bucketName: 'user_images'
      });
    
      gfs = Grid(connection.db, mongoose.mongo);
      gfs.collection(image_bucket_name);
    
      if (file.contentType === 'image/jpeg' || file.contentType === 'image/png') {
        //now instead of const readstream = gfs.createReadStream(file.filename);
        //add this line
        const readStream = gridFSBucket.openDownloadStream(file._id);
        readSteam.pipe(res);
      }
    });
    

    如果您遇到(DeprecationWarning: GridStore 已弃用,将在未来版本中删除。请改用 GridFSBucket),希望这可以节省您一些时间。

    【讨论】:

      【解决方案3】:

      我按照tutorial 创建了这个食谱。教程很棒,它很好地解释了所有步骤。完整的代码示例可以在here 找到。

      HTML表单示例:

      <form action="http://localhost:4000/upload" method="post" enctype="multipart/form-data">
            <input type="file"  name='image' />
            <button type="submit" >Submit</button>
      </form>
      

      将图像上传到 mongodb 的控制器配方:

      const path = require('path');
      const crypto = require('crypto');
      const mongoose = require('mongoose');
      const multer = require('multer');
      const GridFsStorage = require('multer-gridfs-storage');
      const Grid = require('gridfs-stream');
      
      const mongodbURL="mongodb+srv://<user>:<pass>@cluster.mongodb.net/<databaseName>"
      const connection = mongoose.createConnection(mongoURI);
      
      // Init gfs
      let gfs;
      const image_bucket_name = "user_images"
      
      connection.once('open', () => {
          // Init stream
          gfs = Grid(connection.db, mongoose.mongo);
          gfs.collection(image_bucket_name);
      })
      
      // Create storage engine
      const storage = new GridFsStorage({
          url: mongoURI,
          file: (req, file) => {
              return new Promise((resolve, reject) => {
                  crypto.randomBytes(16, (error, buffer) => {
                      if (error) {
                          return reject(error);
                      }
                      const filename = buffer.toString('hex') + path.extname(file.originalname);
                      const fileinfo = {
                          filename: filename,
                          bucketName: image_bucket_name
                      };
                      resolve(fileinfo);
                  })
              });
          }
      });
      
      const upload = multer({ storage });
      app.post('/upload', upload.single('image'), async (req, res) => {
          console.log("uploaded image: "+req.file.
      });
      

      【讨论】:

      • 这个答案使用了 gridfs-stream 包,它首先导致了错误。
      • @Inhinito 您是否尝试过解决方案?它会抛出什么错误?
      • 您提出的解决方案使用已弃用的 GridFS 包,如果您不更新到 GridFSBucket 包,则会引发弃用警告。
      猜你喜欢
      • 2020-12-30
      • 2011-10-10
      • 2011-08-05
      • 2020-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多