如何解决TypeError:User.pre不是函数
我正在尝试实现Node.js端点,如果时间戳和JWT匹配,该端点将更新密码。我在这里使用旧语法吗?我的代码如下:
app.put('/changepassword',function (req,res) {
// https://stackoverflow.com/questions/20277020/how-to-reset-change-password-in-node-js-with-passport-js
// https://www.mongodb.com/blog/post/password-authentication-with-mongoose-part-1
console.log("Password change endpoint was called by",req.ip);
User.pre('save',function (next) {
var user = this;
// only hash the password if it has been modified (or is new)
if (!user.isModified('password')) return next();
// generate a salt
bcrypt.genSalt(SALT_WORK_FACTOR,function(err,salt) {
if (err) return next(err);
// hash the password along with our new salt
bcrypt.hash(user.password,salt,hash) {
if (err) return next(err);
// override the cleartext password with the hashed one
user.password = hash;
next();
});
});
});
UserSchema.methods.comparePassword = function(candidatePassword,cb) {
bcrypt.compare(candidatePassword,this.password,isMatch) {
if (err) return cb(err);
cb(null,isMatch);
});
};
});
我的错误是:TypeError: User.pre is not a function
以下是我的UserSchema。它具有密钥名,姓氏,电子邮件,密码,活动密钥等:
const mongoose = require('mongoose');
const userSchema = mongoose.Schema({
firstname: {
type: String,required: true
},lastname: String,eMail: {
type: String,required: true,unique: true
},password: String,active: Boolean,lastlogin: Date,loginAttempts: { type: Number,default: 0 },lockUntil: { type: Number }
});
/* // expose enum on the model
UserSchema.statics.failedLogin = {
NOT_FOUND: 0,PASSWORD_INCORRECT: 1,MAX_ATTEMPTS: 2
}; */
module.exports = mongoose.model("User",userSchema);
解决方法
您的User
是猫鼬模型,不具有pre
功能。 pre
函数属于中间件。
https://mongoosejs.com/docs/models.html
https://mongoosejs.com/docs/middleware.html#pre
为了执行pre
操作,应将整个pre
函数调用移到声明userSchema
的文件中。 pre
函数是一个挂钩,是您每次调用保存操作时都希望发生的事情。无需在put
函数中声明它。
正如克里斯所说,将以下代码移至UserSchema
文件
User.pre('save',function (next) {
var user = this;
// only hash the password if it has been modified (or is new)
if (!user.isModified('password')) return next();
// generate a salt
bcrypt.genSalt(SALT_WORK_FACTOR,function(err,salt) {
if (err) return next(err);
// hash the password along with our new salt
bcrypt.hash(user.password,salt,hash) {
if (err) return next(err);
// override the cleartext password with the hashed one
user.password = hash;
next();
});
});
});
UserSchema.methods.comparePassword = function(candidatePassword,cb) {
bcrypt.compare(candidatePassword,this.password,isMatch) {
if (err) return cb(err);
cb(null,isMatch);
});
};
完成后,您就可以像这样在您的方法中访问comparePassword
函数,
虚拟请求示例
app.get('/comparePasswords',function (req,res) {
User.findOne(req.id,function (err,user) {
if (err) throw err;
user.comparePassword(req.password,isMatch) {
if (err) throw err;
console.log(isMatch); // -> Returns True if match
});
})
对于ChangingPassword
,我认为您不需要比较密码,但取决于您的用户情况
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。