【发布时间】:2020-12-25 08:06:35
【问题描述】:
目前我能够将密码更新为单个字符串,即使我的架构禁止这样做(要求 minLength 为 7 个字符。)我将在下面发布我的控制器代码,我的问题是,我该如何制作mongoose 验证,在保存之前。
exports.updateUser = async (req, res) => {
const updates = Object.keys(req.body);
const allowedUpdates = ["name", "email", "password", "age"];
const validOp = updates.every((update) => allowedUpdates.includes(update));
if (!validOp) {
return res.status(400).send({ error: "invalid updates" });
}
try {
const user = req.user;
updates.forEach((update) => (user[update] = req.body[update]));
await user.save();
res.send(user);
} catch (err) {
res.status(400).send(err.message);
}
};
User.js(架构、数据库):
const mongoose = require("mongoose");
const validator = require("validator");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
//const Task = require("../models/Task");
const userSchema = new mongoose.Schema(
{
name: {
type: String,
trim: true,
required: true,
},
age: {
type: Number,
default: 0,
validate(value) {
if (value < 0) {
throw new Error("Age must be a postive number");
}
},
},
email: {
type: String,
unique: true,
required: true,
lowercase: true,
validate(value) {
if (!validator.isEmail(value)) {
throw new Error("email is invalid");
}
},
},
password: {
type: String,
required: true,
minLength: 7,
validate(value) {
if (value.toLowerCase().includes("password")) {
throw new Error("password must not contain password");
}
},
},
tokens: [
{
token: {
type: String,
required: true,
},
},
],
avatar: {
type: Buffer,
},
verify: {
type: String,
},
resetPasswordToken: {
type: String,
},
resetPasswordExpires: {
type: Date,
},
},
{
timestamps: true,
}
);
userSchema.virtual("posts", {
ref: "Post",
localField: "_id",
foreignField: "author",
});
userSchema.methods.toJSON = function () {
const user = this;
const userObj = user.toObject();
delete userObj.password;
delete userObj.tokens;
delete userObj.avatar;
return userObj;
};
userSchema.methods.generateAuthToken = async function () {
const user = this;
const token = jwt.sign({ _id: user._id.toString() }, process.env.JWT_SECRET);
user.tokens = user.tokens.concat({ token });
await user.save();
return token;
};
userSchema.statics.findByCredentials = async (email, password) => {
const user = await User.findOne({ email });
if (!user) {
throw new Error("unable to login!");
}
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) {
throw new Error("unable to login!");
}
return user;
};
userSchema.pre("save", async function (next) {
const user = this;
if (user.isModified("password")) {
user.password = await bcrypt.hash(user.password, 8);
}
next()
});
const User = mongoose.model("User", userSchema);
module.exports = User;
更多信息,因为 SO 需要更多信息。
【问题讨论】:
标签: node.js mongodb api mongoose schema