如何创build一个Mongoose方法来写图像到cloudinary

所以我有MEAN栈应用程序(汽车销售),这需要我允许用户上传多个图像到MongoDB的后端。 我select将图像上传到Cloudinary ,然后上传成功,使用Cloudinary返回的图像URL创build一个新文档。

我对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(snippet)

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

所以我自己想了想:

我加了callback方法:

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

然后成功上传我回来了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 });