1
因此,我有MEAN堆棧應用程序(汽車銷售),需要我允許用戶上傳多個圖像到MongoDB後端。我選擇將圖像上傳到Cloudinary,然後在成功上傳時,使用Cloudinary返回的圖像URL創建一個新文檔。如何創建一個Mongoose方法將圖像寫入cloudinary
我對NodeJS/Mongoose相當陌生,所以我不確定我是如何實現我想要做的。以下是我迄今爲止:
var mongoose = require('mongoose');
var cloudinary = require('cloudinary');
var AdSchema = new mongoose.Schema({
sellerEmail: String,
createdAt: { type: Date, default: Date.now },
expiresAt: { type: Date, default: new Date(+ new Date() + 28 * 24 * 60 * 60 * 1000) },
adTitle: String,
price: Number,
currency: String,
phoneNo: String,
county: String,
make: String,
model: String,
year: Number,
engineSize: Number,
fuelType: String,
bodyType: String,
otherMake: String,
otherModel: String,
transmission: String,
miles: Number,
milesKm: String,
taxExpiry: String,
testExpiry: String,
sellerType: String,
description: String,
imageUrls: Array,
mainImage: Number
});
AdSchema.methods.uploadImages = function (images) {
var ad = this.toObject();
if (images.length) {
images.forEach(function (image) {
cloudinary.uploader.upload(image.path).then(function (result) {
ad.imageUrls.push(result.secure_url);
//the images are uploaded to cloudinary as expected and the urls are pushed to imageUrls, but what do I do now?
// not sure what to return when images have been uploaded
});
});
} else {
cloudinary.uploader.upload(images.path).then(function (result) {
ad.imageUrls.push(result.secure_url);
// not sure what to return when image has been uploaded
});
}
}
module.exports = mongoose.model('Ad', AdSchema);
server.js(片段)
//I want to call method above and on success, save the ad
ad.uploadImages(req.files.images, function() {
ad.save(function(err, savedAd) {
//I am fine with this part
});
});