javascript - 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);
解决方案
在 passport.js 文件中,您不需要require('mongoose')
and mongoose.model('User')
,因此删除它们并更改user
为User
:
const passport = require('passport');
const User = require('../schema/user');// change user to User
const LocalStrategy = require('passport-local').Strategy;
推荐阅读
- maven - 使用 Selenium-Cucumber Maven 在每次运行时创建单独的报告目录
- php - 将附件路径推送到数据库表
- ms-access - 当通过另一个表格输入信息时,更新表格中的表格信息
- r - R - 像 excel 这样的计数
- python-3.x - 使用 PyNER 的斯坦福名称实体识别器(NER)不起作用
- batch-file - 如何在命令提示符下使用 CD 命令更改为仅以空格命名的文件夹?
- c# - 在 C# 中,如何使用正则表达式扫描非常大的文件 - 或者是否可以一次提供一个正则表达式一个字符?
- python - 从 discord.py rewrite 发送一个 pm
- c - 如何从 C 中的字符串中打印出所有其他字符?
- angular - 隐藏 Highstocks 滚动条内的折线图