Node.js中MongoDB save函数未进入回调,请求问题排查
save() Callback Not Executing Hey there, let's figure out why your save() callback isn't running—this is a common gotcha with Mongoose, so we'll break down the most likely fixes step by step.
1. First, Validate Your Model Initialization
The iUser model might not be properly set up as a Mongoose document model. Double-check that you defined it correctly elsewhere in your code, like this:
const mongoose = require('mongoose'); const userSchema = new mongoose.Schema({ // Your schema fields (username, password, email, etc.) go here }); const iUser = mongoose.model('User', userSchema); // This line is critical
If iUser wasn't created with mongoose.model(), calling new iUser() might just make a plain JavaScript object instead of a Mongoose document—meaning save() won't trigger the expected database logic or callback.
2. Fix the Promise's Missing resolve() + Switch to Promise Syntax
Right now, your Promise only handles rejection cases—it never calls resolve() when the save succeeds. Even if the save worked, the Promise would hang forever. Worse, callback-based save() can hide silent errors. Let's rewrite it with Promise chains for clearer debugging:
module.exports.registerUser = (userData) => { return new Promise((resolve, reject) => { if (userData.password !== userData.password2) { reject("Passwords do not match!"); return; // Exit early to avoid unnecessary code } console.log(userData); let newUser = new iUser(userData); console.log(newUser); // Use .then/.catch instead of callbacks for better error visibility newUser.save() .then(savedUser => { console.log("REACHED"); resolve(savedUser); // Resolve with the successfully saved user }) .catch(err => { console.log("Full save error:", err); // Log the complete error to debug reject(err.code === 11000 ? 'Username already taken!' : `Error creating User...`); }); }); }
3. Check Your MongoDB Connection Status
If Mongoose isn't connected to MongoDB, it will queue database operations indefinitely. Add this line right before creating newUser to confirm your connection state:
const mongoose = require('mongoose'); console.log("MongoDB connection state:", mongoose.connection.readyState); // 0 = disconnected, 1 = connected, 2 = connecting, 3 = disconnecting
If the state is 0 or 3, fix your connection setup first—make sure you're calling mongoose.connect() with the correct URI and handling connection errors.
4. Enable Mongoose Debug Mode
Turn on debug logging to see exactly what Mongoose is doing under the hood. Add this line at the top of your file where you initialize Mongoose:
mongoose.set('debug', true);
This will log all database operations to the console, so you can confirm if the save() command is even being sent to MongoDB.
5. Check for Schema Validation Errors
Mongoose runs schema validation before saving—if your userData is missing required fields or doesn't match schema rules, save() might fail silently. You can add a manual validation check to catch this early:
const validationError = newUser.validateSync(); if (validationError) { console.log("Validation failed:", validationError); reject(validationError.message); return; }
Try these steps one by one—chances are the issue is either a misconfigured model, a missing database connection, or unhandled validation errors.
内容的提问来源于stack exchange,提问作者user9399000

