首页 > 解决方案 > Passport.js 抛出错误,MissingSchemaError(name)

问题描述

尝试对后端进行编码,这会在控制台中引发错误。可能是什么问题呢?我根据要求导入了 user.js,但仍然无法正常工作。

错误: mongoose.Error.MissingSchemaError(name); Schema hasn't been registered for model "User". Use mongoose.model(name, schema)

Passport.js

const passport = require('passport');
const user = require('../schema/user');
const LocalStrategy = require('passport-local').Strategy;
const mongoose = require('mongoose');
const User = mongoose.model('User');

 
passport.use(new LocalStrategy({
  usernameField: 'email'
},
(username, password, done) => {
  User.findOne({ email: username }, (err, user) => {  
     if (err) { return done(err); }
     if (!user) {
        return done(null, false, {
            message: 'Incorrect username.'
        });
     }
     if (!user.validPassword(password)) {  
        return done(null, false, {
           message: 'Incorrect password.'
        });
     }
     return done(null, user);  
  });
}
));

用户.js

const mongoose = require("mongoose");
const crypto = require('crypto');  
const jwt = require('jsonwebtoken');


const userSchema = new mongoose.Schema({
   email: {
      type: String,
      unique: true,
      required: true
   },
   name: {
      type: String,
      required: true
   },
   hash: String,
   salt: String
});

userSchema.methods.setPassword = function (password) {  
  this.salt = crypto.randomBytes(16).toString('hex');
  this.hash = crypto
  .pbkdf2Sync(password, this.salt, 1000, 64, 'sha512')  
  .toString('hex');
  };

userSchema.methods.validPassword = function (password) {
    const hash = crypto
    .pbkdf2Sync(password, this.salt, 1000, 64, 'sha512')
    .toString('hex');
    return this.hash === hash;
};

userSchema.methods.generateJwt = function () {
    const expiry = new Date();
    expiry.setDate(expiry.getDate() + 7);  
    return jwt.sign({
    _id: this._id,
    email: this.email,
    name: this.name,
    exp: parseInt(expiry.getTime() / 1000, 10),  
    }, process.env.JWT_SECRET );  
};
 

module.exports = mongoose.model('User', userSchema);

标签: javascriptexpressmongoosepassport.js

解决方案


在 passport.js 文件中,您不需要require('mongoose')and mongoose.model('User'),因此删除它们并更改userUser

const passport = require('passport');
const User = require('../schema/user');// change user to User
const LocalStrategy = require('passport-local').Strategy;

推荐阅读