I have used filepond to upload files on react :

<FilePond files={this.state.files} allowMultiple={true} server="http://localhost:5000/api/upload" onupdatefiles={(fileItems) => { this.setState({ files: fileItems.map(fileItem => fileItem.file) }); this.handleFileMetadata(); }} />

Now to handle the file upload I am using express

router.post('/upload', (req, res) => {
// logic to store file on mongodb
})

To delete the temp files that are uploaded, filepond sends a DELETE req to the server mentioned above

So I use

router.delete('/upload', (req, res) => {
})

But I cant delete the file from mongodb, how do I delete it without any attributes?

1 Answers

0
shaochuancs On Best Solutions

To delete the file record in MongoDB, you need to declare which file record needs to be deleted. Anyway, MongoDB doesn't know your intention automatically.

There are several ways to declare the file record:

  • (Recommended solution) In POST /upload router, return the inserted file record id to frontend (e.g. 5b88a6b213d0613d198d7ecf). Then, in the following DELETE /upload/:recordId request, frontend would pass that inserted file record id to backend, e.g. DELETE /upload/5b88a6b213d0613d198d7ecf. Next, Node.js code can extract the to-delete file id and make corresponding operation in MongoDB.
  • If it is a temporary file and needs to be deleted immediately after the upload, and you can't follow the above solution for whatever reason (weird situation), you can use Session if the web application is session-based: In POST /upload router, store latestFileId in session and retrieve the latestFileId session value in the next DELETE /upload request.
  • If it is a temporary file and needs to be deleted immediately after the upload, and you can't follow the first solution for whatever reason (weird situation), and the web application is session-less, you can use Cookie: In POST /upload router, send latestFileId to browser using Set-Cookie and retrieve the latestFileId cookie value in the next DELETE /upload request.