skip to Main Content

When I’m making multiple upload it’s working fine, but when I’m uploading single file it doesn’t work. it says TypeError: req.body.file.map is not a function

I don’t know what’s happening here. is it because I map already the req.body?

    exports.create = (req, res) => {
    const { name, description, price, category, quantity, url } = req.body
    if (!name || !description || !price || !category || !quantity ) {
        return res.status(400).json({
            error: "All fields must be filled"
        })
    }

    req.body.images = req.body.file.map(function (obj) {
      const id = mongoose.Types.ObjectId();
      return {
        url: obj,
        id: id,
        isApproved: false,
      };
    });

    req.body.shop = req.params.shopId;
    let product = new Product(req.body);

    var product_images = req.files;
    var arrayofId = product_images.map(function (obj) {
        return obj.id;
    })


    product.save((err, result) => {
        if (err) {
            return res.status(400).json({
                error: `Error on saving product: ${dbErrorHandler(err)}`
            });
        }
        connection.db.collection("productimage.files", function(err, collection){
            if (err) {
                return res.status(400).json({
                    error: `Error on saving image: ${dbErrorHandler(err)}`
                });
            }   
            collection.updateMany({
                _id:
                    {
                        $in: arrayofId
                    }
            }, {
                $set: { aliases: [result._id.toString()] }
            });
        });
        res.json(result);
    });
    
};

This is my uploadProduct

    export const addProduct = async (productData, shopId, url) => {
    const ls = new SecureLS({ encodingType: "aes" });

    const token = ls.get("token");

    const formdata = new FormData();


    for (let index = 0; index < productData.images.length; index++) {
        formdata.append("file", productData.images[index]);
    }

    formdata.append("category", productData.category);
    formdata.append("name", productData.name);
    formdata.append("quantity", productData.quantity);
    formdata.append("price", productData.price);
    formdata.append("description", productData.description);
    formdata.append("ingredients", productData.ingredients);
    formdata.append("url", url);

    return await fetch(`${API}/product/${shopId}`, {
        method: "POST",
        headers: {
            Authorization: `Bearer ${token}`,
        },
        body: formdata,
    })
        .then((response) => {
            return response;
        })
        .catch((err) => {
            //console.log(err)
            return err;
        });
};

I’m wanting to also be able to upload a single file.

2

Answers


  1. It’s because when you upload single file, req.body.file is not an array.

    In your upload function:

    for (let index = 0; index < productData.images.length; index++) {
         formdata.append("file", productData.images[index]);
    }
    

    you should change to

    for (let index = 0; index < productData.images.length; index++) {
         formdata.append("file[]", productData.images[index]);
    }
    
    Login or Signup to reply.
  2. when you upload multiple files it becomes an array and your map function works perfectly.
    but when you upload a single file it’s not an array and you get the array.
    the map is an array function.

    for example:

    let req = {body: {
        file: []
        
    }};
    req.body.file.map(x=>something);

    the above function will work perfectly but if you do like this

    let req = {body: {
        file: "value"
        
    }};
    req.body.file.map(x=>something);

    this will through error "req.body.file.map is not a function"

    Solution
    send files data in the array from the client-side even if a single file
    or
    check file if is an array the apply the map otherwise treat this single file

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search