I am trying to make a website where users can upload several images and have those images uploaded to Cloudinary and displayed on their post. Everything is working fine except I cannot get the URLs of the images to save to mongoDB or display properly. Here is my code:
var imageLength;
var newImage = [];
router.post("/", isLoggedIn, upload.array("image"),function(req, res){
imageLength = req.files.length;
for(var i = 0; i < imageLength; i++){
cloudinary.uploader.upload(req.files[i].path, function(result) {
// add cloudinary url for the image to the campground object under image property
newImage.push(result.secure_url);
req.body.campground.image[i].push(newImage[i]);
});
}
// add author to campground
req.body.campground.author = {
id: req.user._id,
username: req.user.username
};
Campground.create(req.body.campground, function(err, campground) {
if (err) {
return res.redirect('back');
}
for(var i = 0; i < imageLength; i++){
}
res.redirect('/campgrounds/' + campground.id);
});
return imageLength = req.files.length;
});
Here is the model for "Campground":
var mongoose = require("mongoose");
var campgroundSchema = new mongoose.Schema({
name: String,
image: [String],
image_id: [String],
description: String,
author: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
username: String
},
comments: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Comment"
}
]
});
module.exports = mongoose.model("Campground", campgroundSchema);
And here is where I am displaying their images on their post:
<% for(var i = 0; i < campground.image.length; i++){ %>
<img class="img-responsive" src="<%= campground.image[i] %>">
<% } %>
This is the error I am receiving:
/home/ubuntu/workspace/YelpCamp/v10/routes/campgrounds.js:47
req.body.campground.image[i].push(newImage[i]);
^
TypeError: Cannot read property '1' of undefined
at /home/ubuntu/workspace/YelpCamp/v10/routes/campgrounds.js:47:38
at IncomingMessage.<anonymous> (/home/ubuntu/workspace/YelpCamp/v10/node_modules/cloudinary/lib/uploader.js:500:51)
at emitNone (events.js:91:20)
at IncomingMessage.emit (events.js:185:7)
at endReadableNT (_stream_readable.js:974:12)
at _combinedTickCallback (internal/process/next_tick.js:80:11)
at process._tickCallback (internal/process/next_tick.js:104:9)
console.log(req.body)show ?imageproperty in this. That's why you get error sayingCannot read property 'push' of undefined