【发布时间】:2018-08-11 22:16:14
【问题描述】:
我正在构建一个快速应用程序,该应用程序具有一个可以选择上传单个图像的表单。我已经使用 cloudinary sdk for node.js nad 实现了图像上传,返回成功。我可以在我的控制台中看到图像 url 并对其进行测试以确保。喜欢:
Product Cloud Image URL: http://res.cloudinary.com/joey17/image/upload/v1520120085/bte0bhzl6ljcuqmr3vgn.jpg
img url value: http://res.cloudinary.com/joey17/image/upload/v1520120085/bte0bhzl6ljcuqmr3vgn.jpg
当我尝试在 mongodb 中保存此路径时出现问题。我有这个 sn-p 来保存表单中的输入和图像,如下所示:
let imgUrl = "";
cloudinary.uploader.upload(req.files.image.path, (resultImage) => {
console.log('Product Cloud Image URL:\t' + resultImage.url);
imgUrl = resultImage.url;
console.log('img url value:\t' + imgUrl);
});
Products.findOne({slug: slug})
.select('_id title slug image desc price category')
.exec()
.then(product => {
if (product) {
req.flash('danger', 'Product Title Already Exists');
res.render('admin/add_product', {
title: title,
slug: slug,
price: price,
desc: desc,
category: cat,
image: imgUrl
});
} else { // start reading from here... sorry had to include the other parts above
console.log('Unique Product Slug');
let price2 = parseFloat(price).toFixed(2);
let product = new Products({
title: title,
slug: slug,
price: price2,
desc: desc,
category: cat,
image: imgUrl
});
product.save()
.then(data => {
console.log('Product Created:\t' + data);
req.flash('success', 'New Product Created');
res.redirect('/admin/products');
})
.catch(e => {
console.error('Error Saving Product:\t' + e);
});
}
})
.catch(err => {
console.error(err);
});
}
});
在 mongo compass 中,我检查过,但图像的值是一个空字符串,例如:' '。这是新创建的产品的 sn-p:
_id: ObjectId("5a9b307937766901104addf8")
title: "Blue Shirt"
slug: "blue-shirt"
price: 123
desc: "a blue ocean"
category: "clothes"
image: ""
__v: 0
我不明白为什么不保存 cloudinary 路径。请有人帮我解决这个问题。谢谢。
【问题讨论】:
-
我的错,我应该将产品保存在 cloudinary 回调中。第一个对此答案发表评论的人将被接受。提前致谢。
标签: node.js mongodb image express cloudinary