我正在尝试设置图像计数的限制。关键是我已经在 Mongoose 中设置了它,但就图像上传到云而言,我认为应该在上传之前添加一些东西,并首先检查图像数组的长度是否小于 4。这是代码。
獴
const userSchema = new mongoose.Schema({
username: { type: String },
email: { type: String },
isVerified: { type: Boolean, default: false },
picVersion: { type: String, default: '1531305955' },
picId: { type: String, default: 'default.png' },
images: {
type:[{
imgId: { type: String, default: '' },
imgVersion: { type: String, default: '' }
}],
validate: [arrayLimit, 'You can upload only 4 images']
},
city: { type: String, default: '' },
});
function arrayLimit(val) {
return val.length <= 4;
}
控制器
UploadImage(req, res) {
// check if images array length is <== 4 and then let bellow function
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' })
);
});
},
我应该在cloudinary.uploader.upload(req.body.image, async result => {
之前添加什么先检查一下?
好吧,
你实际上可以改变你做更新伙伴的方式。我建议您使用 findOne() 然后使用更新您的用户,因为这样做时,您可以更好地控制更新,而不仅仅是使用 update。所以在这里尝试这样
UploadImage(req, res) {
User.findOne({ _id: req.user._id })
.then((user) => {
if (user) {
if (user.images.type.length <= 4) {
cloudinary.uploader.upload(req.body.image, async result => {
user.image.type.push({ imgId: result.public_id, imgVersion: result.version });
user.save()
.then(res.status(HttpStatus.OK).json({ message: 'Image uploaded successfully' }))
.catch(); //use callback inside save() or use it like promise
});
}
} else { res.status(HttpStatus.INTERNAL_SERVER_ERROR).json({ message: 'Error uploading image' }); }
})
.catch(err => res.status(HttpStatus.INTERNAL_SERVER_ERROR).json({ message: 'Error uploading image' }));
}
通过这样做,您可以实现您正在寻找的东西..干杯:)