无法通过Postman/Thunder客户端上传图片到MongoDB

问题描述 投票:0回答:1

因此,当我尝试为电子商务网站项目添加产品时,除了图像之外,该产品的所有详细信息都已成功传输到 MongoDB,而我得到的是一个空数组。

这是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}

这是 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

这是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

最后,这是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

以下是Postman和MongoDB的图像截图

对象(Product)的字段Key和Data

结果显示产品添加成功

终端显示图像的空数组

邮递员控制台显示“没有引用图像的此类文件”

MongoDB 上图像的空数组

我首先验证了该文件的存在。它在我的桌面上。我知道文件路径不会错,因为我正在使用 Postman 的浏览按钮(文件选择器)。

为了调试,我将此代码添加到 productsController.js 中的 addProduct 函数中

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

这是我在终端中得到的:

{ name: '测试名称', 描述:'测试描述', 类别:“男士”, 价格:10, 子类别:“上衣”, 畅销书:真实, 尺寸:['M'], 图像: [], 日期:1736191821156 } 请求文件:[对象:空原型] {} 请求正文:[对象:空原型] { name: '测试名称', 描述:'测试描述', 价格:'10', 畅销书:“真实”, 类别:“男士”, 子类别:“上衣”, 尺寸:'[“M”]' }

这确认了 req.files 为空

我还使用了 console.log() 来检查 multer 中间件是否正在执行,确实如此。

我也重启了服务器,但还是不行

node.js mongodb postman multer
1个回答
0
投票

您遇到的是邮递员 vscode 扩展的“已知问题”。您可以订阅此对话以跟踪修复情况。在此之前,请使用邮递员桌面应用程序或任何其他客户端

© www.soinside.com 2019 - 2024. All rights reserved.