You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

提交必填字段仍触发Mongoose ValidatorError问题求助

Mongoose ValidatorError: Path email is required even when required fields are submitted

Hey there, let's break down why you're hitting this validator error even though you included the email field in your request.

Root Cause 1: Invalid JSON Format in Your Curl Request

JSON strictly requires double quotes for keys and values, but your curl command uses single quotes inside the payload. Shell environments can mess up the parsing when you mix quote types incorrectly, leading to Express not being able to read the email field from the request body at all. That's why Mongoose thinks the field is missing!

Fix the Curl Command

Use one of these corrected commands to send valid JSON:

# Option 1: Escape double quotes inside the outer double quotes
$ curl -v http://localhost:3000/api/users --data "{ \"user_name\":\"xsa\", \"email\":\"foo@bar.baz\" }"

# Option 2: Wrap the entire JSON payload in single quotes (cleaner)
$ curl -v http://localhost:3000/api/users --data '{ "user_name":"xsa", "email":"foo@bar.baz" }'

Root Cause 2: Missing Body Parsing Middleware (Double Check!)

Even with valid JSON, Express won't parse the request body into req.body unless you've set up the appropriate middleware. Make sure your main Express app file has this line:

const express = require('express');
const app = express();

// This parses JSON request bodies
app.use(express.json());

Bonus: Fix Your Route Handler

Your current route has a small mistake in the callback parameters (third param should be next, not err) and doesn't handle successful saves. Here's a cleaned-up version:

router.post('/users', (req, res, next) => {
  const user = new User(req.body);
  user.save()
    .then(savedUser => {
      res.status(201).json(savedUser); // Send success response
    })
    .catch(err => {
      res.status(400).send(err); // Use 400 status for validation errors
    });
});

Once you fix the curl JSON format and confirm the body parser is set up, Mongoose should recognize the email field and pass validation.

内容的提问来源于stack exchange,提问作者xsa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:48:32