0

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)
5
  • can you please show what console.log(req.body) show ? Commented Apr 5, 2018 at 15:25
  • @Usman Rana When I console.log(req.body) right before i try to push newImage[i] into req.body.campground.image I recieve this: { campground: { name: 'f', description: 'f', author: { id: 5aaaf25986f338289129f8ea, username: 'frff' } } } Commented Apr 5, 2018 at 17:06
  • there is no image property in this. That's why you get error saying Cannot read property 'push' of undefined Commented Apr 6, 2018 at 6:37
  • @UsmanRana How would I go about adding the image property? I've added it to the model and I've dropped the collection in mongo but I am still receiving the error. Commented Apr 6, 2018 at 15:34
  • @GeorgeBailey Do you have any advice on how I should continue? Thank you for your help so far. Commented Apr 9, 2018 at 19:33

1 Answer 1

1

You are tying to push items into an array with an index. Remove the index and push the items directly into the image object. Replace req.body.campground.image[i].push(newImage[i]); With req.body.campground.image.push(newImage[i]);

Sign up to request clarification or add additional context in comments.

1 Comment

I now receive the error: "Cannot read property 'push' of undefined". This is the same error I had when I tried several other methods to accomplish this task. It's as if it's treating the model as null but the syntax looks correct to me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.