【问题标题】:Passport.js throws error, MissingSchemaError(name)Passport.js 抛出错误,MissingSchemaError(name)
【发布时间】:2021-04-26 02:52:22
【问题描述】:

尝试编写后端代码,这会在控制台中引发错误。可能是什么问题呢?我根据要求导入了 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);  
  });
}
));

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);

【问题讨论】:

    标签: javascript express mongoose passport.js


    【解决方案1】:

    在passport.js文件中,你不需要require('mongoose')mongoose.model('User'),所以删除它们并将user更改为User,如下所示:

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

    【讨论】:

      猜你喜欢
      • 2020-02-16
      • 2016-11-19
      • 2018-04-20
      • 1970-01-01
      • 2016-04-02
      • 2020-05-30
      • 2018-06-28
      • 1970-01-01
      • 2021-08-04
      相关资源
      最近更新 更多