MongoDB数据存储异常排查:React表单数据未存入faceRecognition库
Got it, let's break down why your registration data isn't making it into the database correctly. The core problem here is a mismatch between your Mongoose schema structure and how you're creating new user documents.
The Root Cause
Looking at your userSchema, you've nested all user fields inside a top-level user object:
const userSchema = new mongoose.Schema({ user:{ name:String, email:String, password:String, entries:Number, joined:{ type:Date, default:new Date() } } });
But in your /register route, you're passing the fields directly at the top level of the document you're creating:
User.create({ name:req.body.name, email:req.body.email, password:req.body.password, entries:0, joined: new Date() }, ...)
Mongoose only saves fields that match your schema's structure. Since your schema expects name, email, etc., to live under the user key, those top-level fields are being ignored. The joined field might seem to work, but that's actually the default value from the schema kicking in—not the value you're passing manually.
Two Fix Options
Choose whichever fits your project's needs:
Option 1: Simplify the Schema (Recommended)
Most user models don't need this nested user object. Remove the nesting to align your schema with how you're creating documents:
const userSchema = new mongoose.Schema({ name: String, email: String, password: String, entries: { type: Number, default: 0 }, // Set default here so you don't need to pass it joined: { type: Date, default: Date.now } // Use Date.now (without parentheses) for better practice });
With this change, your existing /register code will work as-is, and all fields will save correctly.
Option 2: Keep the Nested Structure
If you need to retain the user nested object for some reason, adjust your User.create() call to wrap the fields inside user:
app.post('/register',(req,res)=>{ console.log(req.body,req.body.name); User.create({ user: { // Wrap fields in the user object to match the schema name:req.body.name, email:req.body.email, password:req.body.password, entries:0, joined: new Date() } },(err,user)=>{ if(err){ console.log('ERROR!!'); }else{ console.log(user); res.json(user); } }) });
Bonus Improvements
While you're fixing this, here are a few tweaks to make your code more robust:
- Use
findOne()instead offind()in your/signinroute—you're looking for a single user, sofindOne()returns an object instead of an array, which is easier to work with. - Replace callback functions with
async/awaitfor cleaner, more readable code (avoids callback hell). - Add validation to your schema (e.g., required fields for email/password) to ensure data integrity.
After making these changes, test your registration flow again—your user data should now save fully to the faceRecognition database.
内容的提问来源于stack exchange,提问作者Harsh

