node.js - 架构中的属性值采用默认值而不是 MongoDB/Mongoose 中定义的值
问题描述
我的架构定义
const users = new mongoose.Schema({
name: {
type: String,
required: [true, 'Name is mandatory'],
},
email: {
type: String,
required: [true, 'Email is mandatory'],
unique: true,
validate: [validator.isEmail, 'Invalid Email Format'],
},
role: {
type: String,
enum: ['user', 'admin'],
default: 'user',
},
password: {
type: String,
required: [true, 'Password is mandatory'],
minlength: 10,
select: false,
},
confirmPassword: {
type: String,
required: [true, 'Confirming Password is mandatory'],
validate: {
validator: function (current) {
return current === this.password;
},
message: 'Passwords do not match',
},
},
createdAt: Date,
});
使用这个模式,我建立了一个控制器和路由机制来注册新用户,从 Postman 我发送带有正文的 post 请求:
{
"name": "Postman",
"email": "postman@post.com",
"password": "postman999",
"passwordConfirm": "postman999",
"role": "admin",
"createdAt": "2020-03-12"
}
以下是回复
{
"status": "success",
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVlZDUyNzExMWFhOTJjNzE5ZDI2ODQ5YSIsImlhdCI6MTU5MTAyNzQ3NCwiZXhwIjoxNTk4ODAzNDc0fQ.IgH3D6l9Gk3JmXaLE_PSp6LsZzufqKEbMT-CVSsfLSU",
"data": {
"user": {
"role": "user",
"_id": "5ed527111aa92c719d26849a",
"name": "Postman",
"email": "postman@post.com",
"password": "$2a$12$8dx7QwK4ShTWVuvEBV6qdOX7HA1I9TD9woDhF9W6kaBfEFaWuh2gW",
"__v": 0
}
}
}
即使角色属性的值被显式定义为“ admin ”,架构定义的默认值也被保存在数据库中而不是显式定义的值,并且createdAt属性即使指定了值,也根本不会保存在数据库中。当“required: true”被添加到createdAt或role属性中的任何一个时,它会抛出一个错误,说“用户验证失败:角色:路径role
是必须的。”
解决方案
推荐阅读
- python - 无法使用 python 在 sqlite3 中创建数据库
- angular - Angular:如何在控制台中清除网络(API json)。?
- mysql - SQL 查询获取 11 月之后工资增加的员工
- azure - 将资源部署到 Azure 中的资源组时出现主机名过多错误
- sql - 连接定义中的 Teradata 通配符
- java - 再次选中复选框后音乐不播放
- javascript - 侧面板到顶部。还有其他解决方案吗?
- compile-time - 如何使 proc 可用的编译时间和运行时间
- sql-server - SQL 函数,通过使用参数从表中返回值
- c++ - 字符串到枚举类的失败证明转换