node.jsmongodbpostmanmulter

I can't upload images to MongoDB through Postman/Thunder Client


So when I try to add a product for an E-Commerce website project, all the details of the product are successfully transferred to MongoDB except the images, where I get an empty array instead.

This is productController.js

import { v2 as cloudinary } from "cloudinary"
import productModel from "../models/productModel.js"


//function for adding product
const addProduct = async (req, res) => {
    try {
        
        //getting product details
        const  { name, description, price, category, subCategory, sizes, bestseller } = req.body

        //getting product images
        const image1 = req.files.image1 && req.files.image1[0]
        const image2 = req.files.image2 && req.files.image2[0]
        const image3 = req.files.image3 && req.files.image3[0]
        const image4 = req.files.image4 && req.files.image4[0]

        const images = [image1, image2, image3, image4].filter((item)=> item !== undefined)

        let imagesUrl = await Promise.all(
            images.map(async (item) => {
                let result = await cloudinary.uploader.upload(item.path,{resource_type: 'image'});

                return result.secure_url
            })
        )

        const productData = {
            name,
            description,
            category,
            price: Number(price),
            subCategory,
            bestseller: bestseller === "true" ? true : false,
            sizes: JSON.parse(sizes),
            image: imagesUrl,
            date: Date.now()
        }

        console.log(productData);
        
        const product = new productModel(productData);
        await product.save()

        res.json({success:true, message:"Product Added"})
        
        
    } catch (error) {

        console.log(error)
        
        res.json({success:false, message:error.message})

    }
}

//function for listing products
const listProducts = async (req, res) => {

}

//function for removing product
const removeProduct = async (req, res) => {

}

//function for single product info
const singleProduct = async (req, res) => {

}

export {listProducts, addProduct, removeProduct, singleProduct}

This is multer.js

import multer from "multer";

const storage = multer.diskStorage({
   
    filename:function(req, file,callback){
        callback(null, file.originalname)
    }
})

const upload = multer({storage})

export default upload

This is productModel.js

import mongoose from "mongoose";

const productSchema = new mongoose.Schema({
    name: {type: String, required: true},
    description: {type :String, required: true},
    price: {type: Number, required: true},
    image: {type: Array, required:true},
    category: {type: String, required:true},
    subCategory: {type: String, required:true},
    sizes: {type: Array, required:true},
    bestseller: {type: Boolean},
    date: {type: Number, required:true},
    
})

const productModel = mongoose.models.product || mongoose.model("product", productSchema)
// ^^ If the product model is available, it gets assigned to the variable. Else, a new model is created. 

export default productModel

And finally, this is productRoute.js

import express from 'express'

import {listProducts, addProduct, removeProduct, singleProduct} from '../controllers/productController.js'
import upload from '../middleware/multer.js';

const productRouter = express.Router();

productRouter.post('/add',
 upload.fields([
{name:'image1', maxCount:1}, {name:'image2', maxCount:1}, {name:'image3', maxCount:1},
{name:'image4', maxCount:1}
]), addProduct);
productRouter.post('/remove',removeProduct);
productRouter.post('/single',singleProduct);
productRouter.get('/list',listProducts)

export default productRouter

Following are the images screenshots from Postman and MongoDB

Key and Data of the fields of the object (Product)

Result showing successful addition of product

Terminal showing an empty array for images

Postman console saying 'No such file referring to the images'

Empty array for images on MongoDB

I verified the existence of the file first. It's on my Desktop. I know the file path can't be wrong because I'm using the browse button (the file picker) from Postman.

For debugging I added this code to the addProduct function in productsController.js

console.log("Files received:", req.files);

This is what I got in the Terminal:

{ name: 'testing name', description: 'testing description', category: '"Men"', price: 10, subCategory: '"Topwear"', bestseller: true, sizes: [ 'M' ], image: [], date: 1736191821156 } Request Files: [Object: null prototype] {} Request Body: [Object: null prototype] { name: 'testing name', description: 'testing description', price: '10', bestseller: 'true', category: '"Men"', subCategory: '"Topwear"', sizes: '["M"]' }

This confirms that req.files is empty

I also used a console.log() to check if the multer middleware was being executed and it was.

I also restarted the server but it still doesn't work


Solution

  • What you're experiencing is a known issue with postman vscode extension. Until they fix this, use postman desktop app or any other client