node.js - 如何将 gridStore 替换为 gridFSBucket?

标签 node.js gridfs gridfs-stream

我有这个错误信息:

(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 一起使用,在此先非常感谢!

最佳答案

聚会迟到了,但由于我偶然发现了同样的问题,而现有的答案并没有解决问题,我将继续发布我的发现,以防其他人在 future 偶然发现同样的问题:

// 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

关于node.js - 如何将 gridStore 替换为 gridFSBucket?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59717140/

相关文章:

node.js - 数据库连接的初始化-nodejs

node.js - Gridfs-stream、多方中间件的编码问题

css - Webpack 不会使用 css-loader 和 (react)-css-modules 处理 css

javascript - 我们可以为 mongo gridfs 添加另一个值吗?

python - Pymongo GridFS 输入类型/属性错误

node.js - GridFS:清除所有未引用的文件

node.js - TypeORM 树级联移除

javascript - 在封装上揭示模块与对象文字模式

javascript - 从方法中获取变量

javascript - 在 GridFS、express、mongoDB、node.js 中存储来自 POST 请求的数据流