Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Node.js, PHP and APIs

Mongoose says a required path is missing when you save a document

ErrorValidationError

Short answer

The required validator fails when the value is undefined or null at save time. Almost always the value never reached the model: the request body was not parsed, the field name differs from the schema path, or an update set the field to null. Log the object before save and compare keys.

  • Applies to Mongoose 8, Node.js 22, Express 5
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 1Find out which cause you have

    Print exactly what you pass to the model, just before create or save. The missing key, or its undefined value, shows which cause below applies.

    console.log('body:', req.body);
    console.log(Object.keys(req.body ?? {}));
  2. 2Match what you see, then jump to its fix

    1. 1The log shows body: undefined, or an empty object, while the client clearly sent dataThe request body was never parsed, so req.body is undefinedFix
    2. 2The log shows data, but the key is Name, user_name, or sits one level deeper than the schema expectsThe field name in the request differs from the schema pathFix
    3. 3The error appears on findOneAndUpdate or updateOne, not on save, and only when runValidators is onAn update with validators turns the field into null or removes itFix

What does the error look like?

  • ValidationError
  • Path `name` is required.
  • Path `email` is required.

Cause 1 of 3

The request body was never parsed, so req.body is undefined

1Check

Express leaves req.body undefined until a body-parsing middleware runs. That middleware must be registered before the route.

grep -n "express.json\|express.urlencoded" app.js server.js 2>/dev/null

2Fix

Add the parsers above your routes. A form that uploads files is multipart, and that needs multer.

app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use('/users', usersRouter);

3Verify

Post again and check that the log now shows the fields.

curl -X POST http://localhost:3000/users -H 'Content-Type: application/json' -d '{"name":"Sam","email":"sam@example.com"}'

Confirmed by expressjs.com

Did this fix it?

Cause 2 of 3

The field name in the request differs from the schema path

1Check

Mongoose reads the property named exactly like the schema path. A property with another name leaves the path undefined, and the required validator then fails.

console.log(Object.keys(User.schema.paths));
console.log(Object.keys(req.body));

2Fix

Make both sides use the same key. Rename the form input or JSON property, or map it when you build the document.

const user = new User({
  name: req.body.userName,
  email: req.body.email,
});
await user.save();

3Verify

Save again. A document without the error is returned.

console.log(await User.findById(user._id));

Confirmed by mongoosejs.com

Did this fix it?

Cause 3 of 3

An update with validators turns the field into null or removes it

1Check

Update validators are off by default. When they are on, required fails only when the update explicitly sets the path to null or unsets it, so look for a value that becomes null on that route.

grep -rn "runValidators" src/ 2>/dev/null

2Fix

Send only the fields that really change, and never send null for a required path. Drop empty values before the update.

const changes = Object.fromEntries(
  Object.entries(req.body).filter(([, v]) => v !== null && v !== undefined)
);
await User.updateOne({ _id: id }, { $set: changes }, { runValidators: true });

3Verify

Repeat the update with the same input. It saves without a validation error.

console.log(await User.findById(id));

Confirmed by mongoosejs.com

Did this fix it?

How do I stop it coming back?

  • Parse bodies once, at the top of the app, and keep route handlers free of manual parsing.
  • Validate request input at the edge, so Mongoose is the second line of defence and not the first.
  • Use one naming style for client keys and schema paths.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Which stack is behind this page?

Projects of mine built on the same technologies:

Related fixes

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.