How can I delete a file with multer gridfs storage?

老子叫甜甜 提交于 2021-02-11 14:35:05

问题


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);
    });
});

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('/');
  });
});

I get this error in Postman:

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

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!


回答1:


Have you tried this

// @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) DeprecationWarning: collection.remove is deprecated. Use deleteOne, deleteMany, or bulkWrite instead.

and

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

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

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


来源:https://stackoverflow.com/questions/58543984/how-can-i-delete-a-file-with-multer-gridfs-storage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!