Node.js+MongoDB登录接口报错求助:isMatch未定义
Fixing "ReferenceError: isMatch is not defined" in Node.js Auth Server
Let's break down your error first: the server crashes because the variable isMatch isn't defined when your comparePassword method runs. This happens in /models/user.js at line 33, which is part of your user schema's custom method for password verification.
Why This Happens
The isMatch variable is supposed to come from Bcrypt's password comparison logic. It looks like you either:
- Forgot to include
isMatchas a parameter in the Bcrypt callback - Misspelled the variable name (e.g.,
ismatchinstead ofisMatch) - Tried to use
isMatchoutside the scope where it’s defined
Solution: Fix the comparePassword Method
Open your models/user.js file and update the comparePassword method to follow one of these correct patterns:
Option 1: Async Callback Style (Recommended for Non-Blocking Code)
const bcrypt = require('bcrypt'); // ... rest of your user schema definition userSchema.methods.comparePassword = function(candidatePassword, callback) { // Bcrypt's compare method passes the isMatch boolean to the callback bcrypt.compare(candidatePassword, this.password, (err, isMatch) => { if (err) return callback(err); callback(null, isMatch); // Pass the verification result to the callback }); };
Option 2: Sync Style (Simpler, but Blocks the Event Loop)
If you prefer synchronous code, use compareSync:
userSchema.methods.comparePassword = function(candidatePassword) { // compareSync returns the isMatch boolean directly return bcrypt.compareSync(candidatePassword, this.password); };
Steps to Verify
- Save the changes to
user.js - Nodemon should automatically restart your server (if not, manually restart it)
- Test your
POST /signinrequest again with the test credentials
This should resolve the ReferenceError, since isMatch will now be properly defined in the scope where it’s used.
内容的提问来源于stack exchange,提问作者Hello-World
相关产品推荐
相关产品推荐

