Node.js 如何让mongoose运行验证器?
目前,我能够将密码更新为单个字符串,即使我的模式禁止这样做(要求最小长度为7个字符)。我将在下面发布我的控制器代码,我的问题是,如何在保存之前使mongoose验证Node.js 如何让mongoose运行验证器?,node.js,mongodb,api,mongoose,schema,Node.js,Mongodb,Api,Mongoose,Schema,目前,我能够将密码更新为单个字符串,即使我的模式禁止这样做(要求最小长度为7个字符)。我将在下面发布我的控制器代码,我的问题是,如何在保存之前使mongoose验证 exports.updateUser = async (req, res) => { const updates = Object.keys(req.body); const allowedUpdates = ["name", "email", "password&qu
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 bcrypt=require(“bcryptjs”);
const jwt=require(“jsonwebtoken”);
//const Task=require(“../models/Task”);
const userSchema=new mongoose.Schema(
{
姓名:{
类型:字符串,
特里姆:没错,
要求:正确,
},
年龄:{
类型:数字,
默认值:0,
验证(值){
如果(值<0){
抛出新错误(“年龄必须是正数”);
}
},
},
电邮:{
类型:字符串,
独一无二:没错,
要求:正确,
小写:true,
验证(值){
如果(!validator.isEmail(值)){
抛出新错误(“电子邮件无效”);
}
},
},
密码:{
类型:字符串,
要求:正确,
最小长度:7,
验证(值){
if(value.toLowerCase().includes(“密码”)){
抛出新错误(“密码不能包含密码”);
}
},
},
代币:[
{
代币:{
类型:字符串,
要求:正确,
},
},
],
化身:{
类型:缓冲区,
},
核实:{
类型:字符串,
},
resetPasswordToken:{
类型:字符串,
},
resetPasswordExpires:{
类型:日期,
},
},
{
时间戳:对,
}
);
userSchema.virtual(“posts”{
参考:“职位”,
localField:“\u id”,
外域:“作者”,
});
userSchema.methods.toJSON=函数(){
const user=this;
const userObj=user.toObject();
删除userObj.password;
删除userObj.tokens;
删除userObj.avatar;
返回userObj;
};
userSchema.methods.generateAuthToken=异步函数(){
const user=this;
const token=jwt.sign({u id:user.\u id.toString()},process.env.jwt\u SECRET);
user.tokens=user.tokens.concat({token});
等待user.save();
返回令牌;
};
userSchema.statics.findByCredentials=异步(电子邮件、密码)=>{
const user=wait user.findOne({email});
如果(!用户){
抛出新错误(“无法登录!”);
}
const isMatch=wait bcrypt.compare(密码,user.password);
如果(!isMatch){
抛出新错误(“无法登录!”);
}
返回用户;
};
userSchema.pre(“保存”,异步函数(下一步){
const user=this;
if(user.isModified(“密码”)){
user.password=wait bcrypt.hash(user.password,8);
}
下一个()
});
const User=mongoose.model(“User”,userSchema);
module.exports=用户;
更多信息,因为SO需要更多信息。Mongoose文档显示,您可以在保存函数中设置错误回调 作为参考,以下是他们的示例:
var schema = new Schema({
name: {
type: String,
required: true
}
});
var Cat = db.model('Cat', schema);
// This cat has no name :(
var cat = new Cat();
cat.save(function(error) {
assert.equal(error.errors['name'].message,
'Path `name` is required.');
error = cat.validateSync();
assert.equal(error.errors['name'].message,
'Path `name` is required.');
});
谢谢,但我不确定这将如何帮助我进行验证?你是什么意思?当它执行save函数时,如果某些mongoose参数不满足,它应该抛出一个错误并中止保存。您还可以实现类似express validator的功能,这样您就不必依赖数据库来完成所有验证。如果你感兴趣的话我明白你的意思了!不幸的是,我没有收到任何错误,它正在保存不符合要求标准的数据。也就是说,即使我的模式需要7个字符的密码,我也能保存一个1个字符的密码——我不知道为什么这是可能的。有什么想法吗?你能用你的User.js模型更新这篇文章吗,这样我们就可以看看是否有什么东西可能导致了这个问题?
var schema = new Schema({
name: {
type: String,
required: true
}
});
var Cat = db.model('Cat', schema);
// This cat has no name :(
var cat = new Cat();
cat.save(function(error) {
assert.equal(error.errors['name'].message,
'Path `name` is required.');
error = cat.validateSync();
assert.equal(error.errors['name'].message,
'Path `name` is required.');
});