问题描述
我的登录脚本运行正常,但仅记录一条记录,其余所有记录都挂起了,还不返回,还不确定为什么?
它从我的console.log中而不是用户的console.log中检索电子邮件和密码。还可以确认用户的电子邮件确实存在于数据库中
下面是我的基本设置。
用户模型
var mongoose = require("mongoose");
var bcrypt = require("bcrypt");
var passwordString = require("../helper/generateStrongRandomString");
var schema = new mongoose.Schema(
{
email: {
type: String,required: true,unique: true,validate: {
validator: function (v) {
return /^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/.test(
v
);
},message: (props) => `${props.value} is not a valid email address`,},organisation: {
ref: "organisation",type: mongoose.Schema.Types.ObjectId,client: {
ref: "client",required: false,forename: {
type: String,surname: {
type: String,password: {
type: String,default: null,created: {
type: Date,default: Date.Now(),updated: {
type: Date,passwordResetString: {
type: String,{
toJSON: { virtuals: true },toObject: { virtuals: true },}
);
schema.pre("save",function (next) {
var user = this;
if (!user.isNew) {
user.updated = Date.Now();
}
if (user.isNew && !user.password) {
user.passwordResetString = passwordString();
}
if (!user.isModified("password")) {
return next();
}
bcrypt
.hash(user.password,12)
.then((hash) => {
user.password = hash;
next();
})
.catch((err) => console.log(err));
});
schema.pre("save",function (next) {
var user = this;
user.updated = Date.Now();
next();
});
function autopopulate(next) {
this.populate("organisation");
this.populate("client");
next();
}
schema.pre("find",autopopulate);
schema.pre("findOne",autopopulate);
var User = new mongoose.model("user",schema);
module.exports = User;
登录路线
const router = require("express").Router();
const passport = require("passport");
const catchErrors = require("../middlewares/catchErrors");
router.post(
"/login",passport.authenticate("local"),catchErrors(async (req,res) => {
console.log(req.body);
// console.log(req);
})
);
module.exports = router;
Passport JS本地身份验证
passport.use(
new LocalStrategy(
{
usernameField: "email",passwordField: "password",async function (email,password,cb) {
console.log(email,password);
return User.findOne({ email })
.then((user) => {
console.log(user);
if (!user || !bcrypt.compareSync(password,user.password)) {
console.log(26);
return cb(null,false,{
message: "incorrect email or password",});
}
return cb(null,user,{
message: "Logged in successfully",});
})
.catch((err) => console.log(err));
}
)
);
解决方法
对于任何偶然发现此问题的人,我都知道了。我的问题是我的自动填充,上面未显示的组织模型请参见下面的代码。
function autopopulate(next) {
this.populate("organisation");
this.populate("client");
next();
}
这会将组织加载并填充为用户数据的一部分,但是当我的组织加载到用户上并造成无限循环时,它所做的事情完全相同。
很多注释掉了代码,然后进行确认。
注意无限循环。