Problem
Mongoose pre-save hook (line 22 of User.js) returns early without calling next() when password isn't modified. This can cause middleware chain issues.
Technical Details
File: backend/models/User.js
Line: 22
UserSchema.pre('save', async function () {
if (!this.isModified('password')) return; // Early return without next()
const salt = await bcrypt.genSalt(10);
this.password = await bcrypt.hash(this.password, salt);
// Missing: next() call after hashing
});
Issues
- Early return without next() (though Mongoose auto-calls in async hooks)
- No error handling if bcrypt fails
- No try-catch for hash operation
Recommended Solution
Explicit next() calls and error handling:
UserSchema.pre('save', async function (next) {
try {
// Only hash if password is modified
if (!this.isModified('password')) {
return next();
}
// Hash password with salt
const salt = await bcrypt.genSalt(10);
this.password = await bcrypt.hash(this.password, salt);
// Explicitly call next
next();
} catch (err) {
// Pass error to next middleware
next(err);
}
});
Alternative: Using async pattern without next()
UserSchema.pre('save', async function (next) {
if (!this.isModified('password')) {
return next();
}
try {
this.password = await bcrypt.hash(this.password, 10);
} catch (err) {
throw err; // Let Mongoose handle
}
});
Testing Strategy
Program Template
Suggested Labels
reliability, middleware, mongoose, gssoc-eligible
Problem
Mongoose pre-save hook (line 22 of User.js) returns early without calling next() when password isn't modified. This can cause middleware chain issues.
Technical Details
File:
backend/models/User.jsLine: 22
Issues
Recommended Solution
Explicit next() calls and error handling:
Alternative: Using async pattern without next()
Testing Strategy
Program Template
Suggested Labels
reliability, middleware, mongoose, gssoc-eligible