【发布时间】:2021-09-15 03:22:12
【问题描述】:
我有一个 Node Js-Express 后端和 Cloudinary 用于图像存储,用于将博客添加到数据库。我已将其配置为输入基本的博客详细信息,例如标题、类别、图像等。到目前为止,所有 CRUD 操作都运行良好。
一个博客上传了多张图片。如果用户必须对给定的博客执行更新操作,则用户可以更新数据库中的一个或多个图像。但由于图像是通过 Cloudinary 存储提供的,因此图像也需要在那里更新。我对如何将更新逻辑与 cloudinary 关联起来有点困惑。
这是我的 editBlog 控制器到目前为止的样子:
exports.editBlog = async (req, res) => {
const { id } = req.params;
const { title, category, content } = req.body;
const blogImages = req.files; // There might be only single image passed to edit instead of all 3 images (for example)
try {
if (!blogImages) {
return res.status(400).json({ message: 'No images attached!' });
}
const updated_images = await Promise.all(blogImages.map((img) => cloudinaryUploadImage(img.path)));
const updates = {};
if (req.body) {
updates.title = title;
updates.category = category;
updates.content = content;
updates.images = updated_images;
}
const updated_data = await Blog.findOneAndUpdate(
{ _id: id },
{
$set: updates
},
{
new: true
}
);
if (!updated_data) {
res.status(200).json({ message: 'Data does not exist' });
return;
}
res.status(200).json({ message: 'Data updated', result: updated_data });
} catch (error) {
res.status(500).json({ message: 'Internal server error', error });
}
};
cloudinaryUploadImage 函数:
const cloudinaryUploadImage = async image => {
return new Promise((resolve, reject) => {
cloudinary.uploader.upload( image , (err, res) => {
if (err) return res.status(500).send("upload image error")
resolve({
img_url: res.secure_url,
img_id: res.public_id
});
}
)
})
}
我不想用不必要的文件填满我的云存储。如果需要更换一张图片,则应从存储中删除旧图片。
如果有人能通过对这段代码进行一些调整来帮助我实现这一目标,我将不胜感激。
提前致谢
【问题讨论】:
标签: node.js express mongoose cloudinary