如何创建一个Mongoose方法将图像写入cloudinary

时间:2016-10-04 20:27:49

标签: node.js mongodb cloudinary

所以我有MEAN堆栈应用程序(汽车销售),它要求我允许用户将多个图像上传到MongoDB后端。我选择将图像上传到Cloudinary,然后成功上传,创建一个新文档,其中包含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
    });
});

1 个答案:

答案 0 :(得分:1)

所以我自己弄清楚了:

我添加了回调方法:

AdSchema.methods.uploadImages = function (images, callback)

然后成功上传时我返回了回调:

return callback(null, ad);

然后这样叫:

ad.uploadImages(req.files.images, function(err, callback) {
    if(err) {
        return res.status(400).send({
            message: 'there was an error creating your ad. Your card has not been charged'
        });
    }
    //save ad
});