gpt4 book ai didi

node.js - Mongoose .pre ('save' ) 未触发 - bcrypt

转载 作者:太空宇宙 更新时间:2023-11-04 03:21:49 24 4
gpt4 key购买 nike

我一直在尝试创建一个简单的身份验证应用程序,但当我尝试在 Mongodb 中保存哈希密码时,遇到 .pre('save') 中间件根本不触发的问题。这是我的 Model.js 文件。

import mongoose from 'mongoose';
import bcrypt from 'bcryptjs';

const userSchema = new mongoose.Schema({
auth_method: {
type: String,
enum: ['local', 'google', 'facebook'],
required: true
},
email: {
type: String,
lowercase: true,
unique: true
},
local: {
password: {
type: String
}
},
google: {
id: {
type: String
}
},
facebook: {
id: {
type: String
}
}
},
{
collection: 'Users'
});

const userModel = module.exports = mongoose.model('Users', userSchema);

userSchema.pre('save', function (next) {
console.log("this:",this); // Nothing prints to the console here
if (this.auth_method !== 'local') {
next();
}
bcrypt.genSalt(10, function (error, salt) {
if (error) throw error;
bcrypt.hash(this.local.password, salt, function (err, hashPassword) {
if (err) throw err;
else {
this.local.password = hashPassword;
next();
}
});
});
});

const comparePassword = (candidatePassword, hashPassword) => {
return new Promise((resolve, reject) => {
bcrypt.compare(candidatePassword, hashPassword, (err, isMatch) => {
if (err) reject(err);
resolve(isMatch);
});
});
};

const saveUser = (user) => user.save();

const findUserByEmail = (email) => userModel.findOne({ email });

const findUserById = (id, cb) => { userModel.findById(id, cb); };

module.exports = {
userModel,
comparePassword,
saveUser,
findUserByEmail,
findUserById
};

感谢任何帮助,我已经尝试了其他线程中建议的所有可能的解决方案,但没有一个有效,包括返回下一个(this)即使在数据库中,也没有 local: {password: 'hashedPassword'}

的字段

最佳答案

您正在编译模型const userModel = module.exports = mongoose.model('Users', userSchema);在创建 userSchema.pre Hook 之前。

正确顺序:

...
userSchema.pre('save', function (next) {
console.log("this:",this); // Nothing prints to the console here
if (this.auth_method !== 'local') {
next();
}
bcrypt.genSalt(10, function (error, salt) {
if (error) throw error;
bcrypt.hash(this.local.password, salt, function (err, hashPassword) {
if (err) throw err;
else {
this.local.password = hashPassword;
next();
}
});
});
});
const userModel = module.exports = mongoose.model('Users', userSchema);
...

看看这个简单的代码:http://devsmash.com/blog/password-authentication-with-mongoose-and-bcrypt

关于node.js - Mongoose .pre ('save' ) 未触发 - bcrypt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49302226/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com