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

How to create a Mongoose method to write images to cloudinary

所以我有一个 MEAN 堆栈应用程序(汽车销售),它要求我允许用户将多张图片上传到 MongoDB 后端。我选择将图像上传到 Cloudinary,然后在成功上传后,使用 Cloudinary 返回的图像 url 创建一个新文档。

我对 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
    });
});

所以我自己想出来了:

我在方法中添加了回调:

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
});