Mongoose Schema报'path is required'错误,请求排查解决
订单创建POST请求验证错误排查与解决
问题背景
在VS Code的Thunder Client中测试创建新订单的POST请求时,遭遇Mongoose验证失败错误。已使用JSON格式发送请求体,但问题未解决;移除Order模型中的required属性后,请求可正常执行。Node.js版本为v18.12.1。
错误信息
{ "msg": "Order validation failed: shippingInfo.phoneNum: Path shippingInfo.phoneNum is required., shippingInfo.pincode: Path shippingInfo.pincode is required., shippingInfo.country: Path shippingInfo.country is required., shippingInfo.state: Path shippingInfo.state is required., shippingInfo.city: Path shippingInfo.city is required., shippingInfo.address: Path shippingInfo.address is required." }
相关代码与请求体
请求体
{ "shippingInfo": { " address": "tunisia", "city": "tunisia", "state": "tunisia", "country": "tunisia", "pincode": 7100, "phoneNum": 11558899 } }
Order模型代码
const mongoose = require("mongoose"); const { Schema } = mongoose; const orderSchema = new mongoose.Schema({ shippingInfo: { address: {type: String,required: true}, city: { type: String, required: true }, state: { type: String, required: true }, country: { type: String, required: true }, pincode: { type: Number, required: true }, phoneNum: { type: Number, required: true }, }, }); const orderModel = mongoose.model("Order", orderSchema); module.exports=orderModel
订单控制器代码
const orderModel = require("../models/orderModel"); //Create new order const newOrder = async (req, res) => { const {shippingInfo}=req.body try { const order= await new orderModel({shippingInfo}) // console.log(shippingInfo) console.log(order) await order.save() res.status(201).send({ order: order, msg: "order added successfully" }) } catch (error) { // console.log(error); res.status(400).send({ msg: error.message }); } }; module.exports = {newOrder };
路由代码
const express = require("express"); const { newOrder } = require("../controllers/orderController"); const isAuth = require("../middlewares/isAuth"); const router = express.Router(); /** * @Params POST /order/neworder * @description create new order * @acces protected */ router.post("/neworder",isAuth(),newOrder); module.exports = router;
原因分析
- 键名格式错误:请求体中
shippingInfo下的address字段键名前多了一个空格(" address"),导致Mongoose无法匹配Schema中定义的address字段,判定该字段缺失。 - Mongoose验证特性:当嵌套对象中存在必填字段缺失时,Mongoose会抛出所有必填字段的验证错误,而非仅提示缺失的那个字段,因此出现所有shippingInfo字段都提示必填的情况。
解决步骤
- 修正请求体键名:将请求体中的
" address"改为"address",去掉键名前的空格,修正后的请求体如下:
{ "shippingInfo": { "address": "tunisia", "city": "tunisia", "state": "tunisia", "country": "tunisia", "pincode": 7100, "phoneNum": 11558899 } }
- 验证请求接收情况:取消控制器中
console.log(shippingInfo)的注释,查看终端输出的shippingInfo对象,确认所有字段键名和值都正确传递。 - 可选:添加键名清理逻辑:若需避免前端传入带空格的键名,可添加一个中间件对请求体的键名进行清理,示例如下:
// 键名清理中间件 const cleanRequestBody = (req, res, next) => { const cleanObj = (obj) => { const result = {}; for (const key in obj) { const cleanedKey = key.trim(); result[cleanedKey] = typeof obj[key] === 'object' && obj[key] !== null ? cleanObj(obj[key]) : obj[key]; } return result; }; req.body = cleanObj(req.body); next(); }; // 在路由中使用 router.post("/neworder", isAuth(), cleanRequestBody, newOrder);
内容的提问来源于stack exchange,提问作者Mnasri Amara
相关产品推荐
相关产品推荐

