问题
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()
andfindOneAndDelete()
without theuseFindAndModify
option set to false are deprecated
this is due to the version of express, multer and GridFs that I'm using
- express: ^4.17.1
- multer: ^1.4.2"
- multer-gridfs-storage: ^3.3.0
来源:https://stackoverflow.com/questions/58543984/how-can-i-delete-a-file-with-multer-gridfs-storage