Mongoose API无法读取请求体数组字段,MongoDB数组字段为空
问题:Mongoose API无法读取数组字段images,存入MongoDB为空
使用Mongoose创建API提交数据到MongoDB,其中包含数组类型字段images。尝试在请求体中以字符串形式(如"['image','image2']")和原生数组形式传递,但服务器端始终无法读取该字段,req.body.images返回undefined,最终存入MongoDB的images字段始终为空,其他字段可正常存储。
请求Payload
{ "name": "name", "description": "description", "price": 123, "image_array": "['image','image2']", "category": "category", "country": "country", "city": "city", "thumbnail": "thumbnail" }
响应
{ "data": { "name": "name", "description": "description", "price": 123, "thumbnail": "thumbnail", "images": [], "category": "category", "country": "country", "city": "city", "user": "633710ae6238121bd9ff4f46", "status": "active", "likes": 0, "_id": "633c794ef9449f8b86c948b0", "createdAt": "2022-10-04T18:19:58.440Z", "updatedAt": "2022-10-04T18:19:58.440Z", "__v": 0 }, "message": "Product added successfully", "Array_type": "undefined" }
路由代码
router.post("/", async (req, res) => { console.log("post product"); try { const newProduct = new Product({ name: req.body.name, description: req.body.description, price: req.body.price, image: req.body.image, category: req.body.category, country: req.body.country, city: req.body.city, user: req.user._id, thumbnail: req.body.thumbnail, }); data = await newProduct.save(); res.status(200).json({ data, message: "Product added successfully", Array_type: typeof req.body.images, }); } catch (err) { console.log(err); res.status(500).json(err); } });
Product Schema
const ProductSchema = new mongoose.Schema( { name: { type: String, required: true }, description: { type: String, required: true }, price: { type: Number, required: true }, thumbnail: { type: String, required: true }, images: [String], category: { type: String, required: true }, country: { type: String }, city: { type: String }, user: { type: mongoose.Schema.Types.ObjectId, ref: "User" }, status: { type: String, default: "active" }, likes: { type: Number, default: 0 }, createdAt: { type: Date, default: Date.now }, updatedAt: { type: Date, default: Date.now }, }, { timestamps: true } );
解决方案
1. 字段名不匹配问题
请求Payload中传递的字段是image_array,但路由中尝试读取的是req.body.images,Schema定义的字段也是images,三者不统一。
修正方式二选一:
- 修改请求Payload,将
image_array改为images,传递原生JSON数组(推荐):{ "name": "name", "description": "description", "price": 123, "images": ["image","image2"], "category": "category", "country": "country", "city": "city", "thumbnail": "thumbnail" } - 或者在路由中读取
req.body.image_array,将字符串形式的数组解析为真实数组(注意替换单引号为双引号,否则JSON.parse会报错):const images = req.body.image_array ? JSON.parse(req.body.image_array.replace(/'/g, '"')) : [];
2. 路由代码未写入images字段
当前路由创建newProduct时完全没有包含images字段,导致即使请求传对值也无法存入数据库,需添加该字段:
情况一:请求传递原生数组
修改路由代码:
router.post("/", async (req, res) => { console.log("post product"); try { const newProduct = new Product({ name: req.body.name, description: req.body.description, price: req.body.price, image: req.body.image, category: req.body.category, country: req.body.country, city: req.body.city, user: req.user._id, thumbnail: req.body.thumbnail, images: req.body.images || [] // 添加这一行 }); data = await newProduct.save(); res.status(200).json({ data, message: "Product added successfully", Array_type: typeof req.body.images, }); } catch (err) { console.log(err); res.status(500).json(err); } });
情况二:请求传递字符串形式数组
修改路由代码,先解析字符串为数组:
router.post("/", async (req, res) => { console.log("post product"); try { let images = []; if (req.body.image_array) { try { images = JSON.parse(req.body.image_array.replace(/'/g, '"')); } catch (parseErr) { console.log("解析images失败:", parseErr); images = []; } } const newProduct = new Product({ name: req.body.name, description: req.body.description, price: req.body.price, image: req.body.image, category: req.body.category, country: req.body.country, city: req.body.city, user: req.user._id, thumbnail: req.body.thumbnail, images: images }); data = await newProduct.save(); res.status(200).json({ data, message: "Product added successfully", Array_type: typeof images, }); } catch (err) { console.log(err); res.status(500).json(err); } });
3. 验证body-parser配置
确保Express应用已正确配置express.json()中间件,否则无法解析JSON格式请求体:
const express = require('express'); const app = express(); app.use(express.json()); // 必须添加这一行
内容的提问来源于stack exchange,提问作者Alex
相关产品推荐
相关产品推荐

