如何删除带有 multer gridfs 存储的文件? [英] How can I delete a file with multer gridfs storage?

查看:68
本文介绍了如何删除带有 multer gridfs 存储的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码按预期工作以上传和检索文件:

The following code works as expected to upload and retrieve files:

// Mongo URI
const mongoURI = 'mongodbconnstring';

// // Create mongo connection
const conn = mongoose.createConnection(mongoURI);

// // Init gfs
let gfs;

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

// Create storage engine
const storage = new GridFsStorage({
  url: mongoURI,
  file: (req, file) => {
    return new Promise((resolve, reject) => {
      const filename = file.originalname; //+ Date.now();
      const fileInfo = {
        filename: filename,
        bucketName: 'Uploads'
      };
      resolve(fileInfo);
    });
  }
});
const upload = multer({ storage });

// // @route POST /upload
// // @desc Uploads file to DB
routerUpload.post('/upload', upload.single('files'), (req, res) => {
  //res.json({file: req.file})
  res.redirect('/');
});

// @route GET /files
// @desc Display all files in json
routerUpload.get('/files', (req, res) => {
  gfs.find().toArray((err, files) => {
    // Check if files
    if (!files || files.length === 0) {
      return res.status(404).json({
        err: 'No files exist'
      });
    }
    return res.json(files);
  });
});

// @route GET /files/:filename
// @desc Display single file object
routerUpload.get('/files/:filename', (req, res) => {
  const file = gfs
    .find({
      filename: req.params.filename
    })
    .toArray((err, files) => {
      if (!files || files.length === 0) {
        return res.status(404).json({
          err: 'No file exists'
        });
      }
      gfs.openDownloadStreamByName(req.params.filename).pipe(res);
    });
});

但是,当我调用下面的代码按 ID 删除文件时:

However, when I call the code below to delete the file by ID:

// @route DELETE /files/:id
// @desc Delete file
routerUpload.post('/files/del/:id', (req, res) => {
  gfs.delete(req.params.id, (err, data) => {
    if (err) {
      return res.status(404).json({ err: err.message });
    }

    res.redirect('/');
  });
});

我在 Postman 中收到此错误:

I get this error in Postman:

{
    "err": "FileNotFound: no file with id 5db097dae62a27455c3ab743 found"
}

任何人都可以指出我需要去的方向吗?我尝试使用delete方法而不是post,甚至指定了文件的根目录,但发生了同样的错误.谢谢!

Can anyone point me in the direction of where I need to go with this? I tried with the delete method instead of post, and even specified the root of the file, but the same error occurs. Thanks!

推荐答案

你试过了吗

// @route DELETE /files/:id
// @desc Delete file
routerUpload.post('/files/del/:id', (req, res) => {
   gfs.remove({ _id: req.params.id, root: "uploads" }, (err, gridStore) => {
            if (err) {
                return res.status(404).json({ err });
            }
            return;

        });
});

但是我使用的是旧版本的快递,因此收到此

However I'm using an old version of express hence receiving this

(node:6024) 弃用警告:不推荐使用 collection.remove.请改用 deleteOne、deleteMany 或 bulkWrite.

(node:6024) DeprecationWarning: collection.remove is deprecated. Use deleteOne, deleteMany, or bulkWrite instead.

(node:6024) DeprecationWarning: Mongoose: findOneAndUpdate()findOneAndDelete() 没有将 useFindAndModify 选项设置为 false 被弃用

(node:6024) DeprecationWarning: Mongoose: findOneAndUpdate() and findOneAndDelete() without the useFindAndModify option set to false are deprecated

这是由于我使用的 express、multer 和 GridFs 版本

this is due to the version of express, multer and GridFs that I'm using

  1. 快递:^4.17.1
  2. multer:^1.4.2"
  3. multer-gridfs-storage: ^3.3.0

这篇关于如何删除带有 multer gridfs 存储的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆