The usual Multer setup saves files right away, as shown in the basic example below:
const multer = require('multer');
const upload = multer({ dest: 'uploads/' });
const app = express();
app.post('/profile', upload.single('avatar'), function (req, res, next) {
// req.file is the `avatar` file
// req.body will hold the text fields, if there were any
// my database-related code...
});
When implementing this code, the image is still saved to the upload folder if an error occurs during the database entry process. I aim to ensure the image is saved only when the database entry succeeds. How can I achieve this?
2
Answers
Tell me one thing do you have separate schema for storing the images(uploads) ????
for example like in mongoose you want to store the image path directly in the document object.
or have separate schema for storing upload and then links vi FID
1:Case One
if you want to store the imgae path directly in the doucment then you have to store the image first let me tell you why??.Because when you’re creating that document and if you have the filed which stores the imagePath and if you haven’t store image then what will you store in that field instaed of image Address ???
Solution
what you can you do here is something called
this will allow you to delete the file in case some error got occur and document is not created.
You can catch the
MulterError
by calling the middleware itself inside the request callback as opposed to before it. If the file saves you can save it’s reference to the database. If the database then errors you can delete the file like so: