im是mongo db的新增功能,我试图将图像的URL保存到mongo db中,但该值未保存。但是当我执行console.log时,URL存在于架构中在.save()之前;
cloudinary.uploader.upload(file.photo.path, { folder: 'products' }, function (err, image) {
if (err) {
return res.status(400).json({
error : "Unable to upload the image"
})
}
console.log(product.photo);
console.log(image.url);
product.photo = image.url;
console.log(product.photo);
console.log(product);
});
console.log(product);
的输出:
{ sold: 0,
_id: 5edc1830887d5801c88420d9,
name: 'ider',
description: 'classic prod',
price: 10,
category: 5ed9258ae973f42bbcbef42b,
stock: 27,
createdAt: 2020-06-06T22:26:56.136Z,
updatedAt: 2020-06-06T22:26:56.136Z,
__v: 0,
photo: 'http://res.cloudinary.com/xxx/image/upload/v1591482420/products/iwsutsgezodvvbyvopnf.png' }
产品的保存:
//save to db
product.save((err, prod) => {
if(err) {
return res.status(400).json({
error : "Saving of product failed"
})
}
res.json(prod);
})
响应:
{
"sold": 0,
"_id": "5edc1830887d5801c88420d9",
"name": "ider",
"description": "classic prod",
"price": 10,
"category": "5ed9258ae973f42bbcbef42b",
"stock": 27,
"createdAt": "2020-06-06T22:26:56.136Z",
"updatedAt": "2020-06-06T22:26:56.136Z",
"__v": 0
}
照片的定义方式是photo: String
完整模式:
const mongoose = require("mongoose");
const { ObjectId } = mongoose.Schema;
const productSchema = new mongoose.Schema(
{
name: {
type: String,
trim: true,
required: true,
maxlength: 32
},
description: {
type: String,
trim: true,
required: true,
maxlength: 2000
},
price: {
type: Number,
required: true,
maxlength: 32,
trim: true
},
category: {
type: ObjectId,
ref: "Category",
required: true
},
stock: {
type: Number
},
sold: {
type: Number,
default: 0
},
photo: String
},
{ timestamps: true }
);
module.exports = mongoose.model("Product", productSchema);
我也用机器人3t检查过,并且分贝中没有照片值
在异步上传完成之前,产品已保存(已在评论中确认)。
将产品保存在图像上传回调中应该可以:
cloudinary.uploader.upload(file.photo.path, { folder: 'products' }, function (err, image) {
if (err) {
return res.status(400).json({
error : "Unable to upload the image"
})
}
//save to db
product.save((err, prod) => {
if(err) {
return res.status(400).json({
error : "Saving of product failed"
})
}
res.json(prod);
})
});