React通过Axios向MongoDB传对象遇Mongoose验证错误求助
Hey, let's break down why you're hitting that Mongoose ValidatorError and fix it step by step!
First: Fix the Express Request Body Parsing (Most Likely Culprit)
The #1 reason you'd get a ValidatorError for required fields here is that Express isn't parsing the JSON body of your POST request. Without the right middleware, req.body will be an empty object {}, so all three fields (img, title, date) will be undefined—triggering Mongoose's required: true checks.
Add this line to your Node.js server setup (before your routes):
const express = require('express'); const app = express(); // This line parses JSON request bodies app.use(express.json()); // Now mount your routes below this app.post('/create-new-memory', (req, res) => { // ... your existing route code });
Second: Verify Your React Data is Actually Populated
Your Schema requires all three fields to have values, but empty strings ("") will also fail the required check. Double-check that the thisListGoesToDB object you're sending from React has real values, not empty strings.
Add a console log in your React onSubmit to confirm:
const onSubmit = async (thisListGoesToDB) => { // Log the data to make sure it's not empty console.log('Submitting data:', thisListGoesToDB); const options = { url: 'http://localhost:5001/create-new-memory', method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json;charset=UTF-8' }, body: JSON.stringify(thisListGoesToDB) }; axios(options) .then(response => console.log('Success!', response.data)) .catch(err => console.log('Error submitting:', err)) };
If you see empty strings here, fix your form's controlled components to properly bind user input to the thisListGoesToDB object.
Third: Clean Up Your Mongoose Save Logic
Your current save() chain has a weird .then().catch().then().catch() structure that can cause unexpected behavior. Let's rewrite it to be clearer:
Option 1: Promise Chaining
app.post('/create-new-memory', (req, res) => { const newListing = new List({ img: req.body.img, title: req.body.title, date: req.body.date }); newListing.save() .then(result => { res.json(result); console.log('Saved successfully'); }) .catch(err => { console.log('Save failed:', err); // Send an error response to the frontend instead of just logging res.status(400).json({ error: err.message }); }); });
Option 2: Async/Await (More Readable)
app.post('/create-new-memory', async (req, res) => { try { const newListing = new List({ img: req.body.img, title: req.body.title, date: req.body.date }); const result = await newListing.save(); res.json(result); } catch (err) { console.log('Save failed:', err); res.status(400).json({ error: err.message }); } });
Fourth: Debug Exact Validation Errors
If you still get the error, log the full error details to see which field is failing:
.catch(err => { console.log('Validation errors:', err.errors); });
This will tell you exactly if img, title, or date is missing/invalid, so you can target the fix.
内容的提问来源于stack exchange,提问作者matan2288

