I am trying to create a post and upload an image if one is provided. If I successfully upload the image, everything works smoothly. However, if I do not upload an image, I encounter the following error:
UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'image' of null
I know that this issue is related to the use of async/await
, but I am unsure how to properly rewrite it or identify the specific problem. Can someone please help me understand and fix it?
app.post("/posts/create", async (req, res) => {
let image = req.files.image;
if (image !== null) {
image.mv(
path.resolve(__dirname, "public/images", image.name)
);
}
await Post.create(req.body);
res.redirect("/");
});