【发布时间】:2021-12-13 13:57:26
【问题描述】:
我正在尝试在 Node.JS 中创建用于重置用户密码的控制器。 这个想法是根据重置密码令牌从数据库中获取用户,进行一些验证更新相关字段并将其保存回数据库。 但是,尝试保存更新的用户时出现错误(“user.save 不是函数”)。 可能是什么原因?
我有一个用户模型定义如下:
const mongoose = require("mongoose");
const validator = require("validator");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const crypto = require("crypto");
const userSchema = new mongoose.Schema({
name: {
type: String,
required: [true, "Please enter valid name"],
maxLength: [30, "Your name cannot exceed 30 characters]"],
},
email: {
type: String,
required: [true, "Please enter valid email"],
unique: true,
validate: [validator.isEmail, "Please enter valid email address"],
},
password: {
type: String,
requires: [true, "Please enter your password"],
minLength: [6, "Your password must be at least 6 characters"],
select: false,
},
avatar: {
public_id: { type: String, required: true },
url: { type: String, required: true },
},
role: { type: String, default: "user" },
createdAt: { type: Date, default: new Date().now },
resetPasswordToken: { type: String },
resetPasswordExpire: { type: Date },
});
userSchema.pre("save", async function (next) {
if (!this.isModified("password")) {
next();
}
this.password = await bcrypt.hash(this.password, 10);
});
// check password matching
userSchema.methods.isPasswordMatched = async function (inputPassword) {
return await bcrypt.compare(inputPassword, this.password);
};
// return JSON Web Token
userSchema.methods.getJwtToken = function () {
return jwt.sign({ id: this.id }, process.env.JWT_SECRET, {
expiresIn: process.env.JWT_EXPIRESIN_TIME,
});
};
// Generate password token
userSchema.methods.getResetPasswordToken = function () {
// Generate Token
const resetToken = crypto.randomBytes(20).toString("hex");
// Hash token
this.resetPasswordToken = crypto
.createHash("sha256")
.update(resetToken)
.digest("hex");
// set expired time
this.resetPasswordExpire = new Date(Date.now() + 30 * 60 * 1000);
return resetToken;
};
module.exports = mongoose.model("User", userSchema);
当我尝试重置用户密码时,我会尝试以下操作:
// get the user document from db (make sure token and expiration time are valid)
let user = User.findOne({
resetPasswordToken: resetPasswordToken,
resetPasswordExpire: { $gt: Date.now() },
});
// update password
user.password = req.body.password;
user.resetPasswordToken = undefined;
user.resetPasswordExpire = undefined;
user.save();
sendToken(user, 200, res);
由于某种原因,我收到一个错误: "errorMsg": "user.save 不是函数"
可能是什么问题?
【问题讨论】: