node.jsexpresscloudinary

TypeError: Cannot read properties of undefined (reading 'map') in Express controller when uploading images to Cloudinary


I'm building a Travel Log app using Node.js/Express, and I have a controller that handles creating a new travel log. Right now, I'm testing my API using Postman (no frontend yet).

Users can optionally upload images (as base64 strings), which get uploaded to Cloudinary. But for now, I'm only testing the endpoint without any images.

However, when I send a POST request, I get the following error: TypeError: Cannot read properties of undefined (reading 'map')

This is the controller code:

export const createTravelLog = async (req, res) => {
  try {
    const {
      userId,
      title,
      description,
      visitedDate,
      location,
      images,
      rating
    } = req.body;
    
    if (!userId || !title || !visitedDate || !location) {
      return res.status(400).json({ message: "These fields are required" });
    }

    if (location.lat < -90 || location.lat > 90) {
      return res.status(400).json({ message: "Invalid latitude" });
    }

    if (location.lng < -180 || location.lng > 180) {
      return res.status(400).json({ message: "Invalid longitude" });
    }

    // Upload images to Cloudinary
    const uploadedImages = await Promise.all(
      images.map(async (image) => {
        const result = await cloudinary.uploader.upload(image, {
          folder: "travel-logs"
        });

        return {
          url: result.secure_url,
          publicId: result.public_id
        };
      })
    );

    const travelLog = new TravelLog({
      user: userId,
      title,
      description,
      visitedDate,
      location,
      images: uploadedImages,
      rating
    });

    await travelLog.save();
    res.status(201).json(travelLog);
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: "Error creating travel log" });
  }
};

i haven't tried anything yet.


Solution

  • This error is telling you that your application is trying to call the .map() function on a value, but that value is undefined. In other words, it's either missing or empty.

    The .map() function only works on arrays. So if images is not defined at all, or it exists but isn't an array, calling .map() on it will throw an error.

    That's why you need to check whether images is actually defined and whether it's an array before using .map(). If it's not, you should fall back to an empty array instead. That way, .map() always runs on an array, and it won't throw an error.

    This is a very common situation when dealing with optional data coming from the user. If you assume that the user will always send a certain field, but sometimes they don't, errors like this happen. It's always good practice to validate incoming data.

        const {
           userId,
           title,
           description,
           visitedDate,
           location,
           images = [], // Set default to an empty array
           rating
        } = req.body;