0

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

// 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 删除文件时:

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

我在邮递员中收到此错误:

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

谁能指出我需要去哪里?我尝试使用 delete 方法而不是 post,甚至指定了文件的根目录,但发生了同样的错误。谢谢!

4

1 回答 1

0

你试过这个

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

        });
});

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

(节点:6024)DeprecationWarning:collection.remove 已弃用。请改用 deleteOne、deleteMany 或 bulkWrite。

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

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

  1. 快递:^4.17.1
  2. 穆尔特:^1.4.2"
  3. multer-gridfs-存储:^3.3.0
于 2019-11-03T00:45:45.293 回答