New*_*ver 3 mongoose node.js express cloudinary
上传和设置默认控制器功能运行良好。然而,我们也正在尝试实现从 Cloudinary 删除图像。如何做呢?在文档中它很混乱。这是代码:
const cloudinary = require('cloudinary');
const HttpStatus = require('http-status-codes');
const User = require('../models/userModels');
cloudinary.config({
cloud_name: 'name',
api_key: 'key',
api_secret: 'secret'
});
module.exports = {
UploadImage(req, res) {
cloudinary.uploader.upload(req.body.image, async result => {
await User.update(
{
_id: req.user._id
},
{
$push: {
images: {
imgId: result.public_id,
imgVersion: result.version
}
}
}
)
.then(() =>
res
.status(HttpStatus.OK)
.json({ message: 'Image uploaded successfully' })
)
.catch(err =>
res
.status(HttpStatus.INTERNAL_SERVER_ERROR)
.json({ message: 'Error uploading image' })
);
});
},
DeleteImage(req, res) {
cloudinary.uploader.destroy(req.params.image, async result => {
await User.update(
{
_id: req.user._id
},
{
$pull: {
images: {
imgId: result.public_id,
imgVersion: result.version
}
}
}
)
.then(() =>
res
.status(HttpStatus.OK)
.json({ message: 'Image deleted successfully' })
)
.catch(err =>
res
.status(HttpStatus.INTERNAL_SERVER_ERROR)
.json({ message: 'Error deleting image' })
);
});
},
async SetDefaultImage(req, res) {
const { imgId, imgVersion } = req.params;
await User.update(
{
_id: req.user._id
},
{
picId: imgId,
picVersion: imgVersion
}
)
.then(() =>
res.status(HttpStatus.OK).json({ message: 'Default image set' })
)
.catch(err =>
res
.status(HttpStatus.INTERNAL_SERVER_ERROR)
.json({ message: 'Error occured' })
);
}
};
Run Code Online (Sandbox Code Playgroud)
我们将 Node.js Express 与 Mongoose 结合使用。我们如何在这里包含额外的功能来删除图像?
小智 5
有两种方法可以从 cloudinary 中删除图像:
cloudinary.v2.api.delete_resources(['image1', 'image2'],
function(error, result){console.log(result);});
cloudinary.v2.uploader.destroy('sample', function(error,result) {
console.log(result, error) });
请注意,使用我们的管理 API 是有速率限制的,您可能需要使用第二个选项。
| 归档时间: |
|
| 查看次数: |
11921 次 |
| 最近记录: |