I was able to successfully upload images in my MongoDB project using Multer, but I’m stuck on how to update them. When I tried using the same trick in my Edit function, the log says I can’t set headers after they’re sent to the client. For context, I’ll put in my code for uploading and editing
router.get('/upload', IsLoggedIn, (req, res, next) => {
res.render('mods/upload', {title: 'Upload a mod', user: req.user});
res.sendFile(path.join(__dirname, './mods/upload.hbs'));
});
router.post('/upload', upload.single('image'), IsLoggedIn, (req, res, next) => {
console.log(req.file);
Mod.create({
name: req.body.name,
image: req.file.filename,
file: req.body.file
}, (err, newMod) => {
if (err) {
console.log(err);
}
else {
res.redirect('/mods');
}
});
});
router.get('/edit/:_id', IsLoggedIn, (req, res, next) => {
Mod.findById(req.params._id, (err, mod) => {
if (err) {
console.log(err);
}
else {
res.render('mods/edit', {
title: 'Edit mod',
mod: mod,
user: req.user
})
}
}).sort({name: 1});
res.render('mods/edit');
res.sendFile(path.join(__dirname, './mods/edit.hbs'));
});
router.post('/edit/:_id', upload.single('image'), IsLoggedIn, (req, res, next) => {
Mod.findOneAndUpdate(
{
_id: req.params._id
},
{
name: req.body.name,
image: req.file.filename,
file: req.body.file
},
(err, updatedProject) => {
if (err) {
console.log(err);
}
else {
res.redirect('/mods');
}
}
)
});
Am I even able to update images in the same fashion, or is there something entirely different I should be doing? I’m still super new to Multer and I haven’t done a whole lot with MongoDB, so any guidance would be super appreciated!