2tr*_*ill 16 javascript mongoose mongodb node.js
我正在尝试使用mongoose在mongodb中保存一个新文档,但ValidationError: Path 'email' is required., Path 'passwordHash' is required., Path 'username' is required.即使我提供的是电子邮件,密码哈希和用户名,我也会收到.
这是用户架构.
var userSchema = new schema({
_id: Number,
username: { type: String, required: true, unique: true },
passwordHash: { type: String, required: true },
email: { type: String, required: true },
admin: Boolean,
createdAt: Date,
updatedAt: Date,
accountType: String
});
Run Code Online (Sandbox Code Playgroud)
这是我创建和保存用户对象的方式.
var newUser = new user({
/* We will set the username, email and password field to null because they will be set later. */
username: null,
passwordHash: null,
email: null,
admin: false
}, { _id: false });
/* Save the new user. */
newUser.save(function(err) {
if(err) {
console.log("Can't create new user: %s", err);
} else {
/* We succesfully saved the new user, so let's send back the user id. */
}
});
Run Code Online (Sandbox Code Playgroud)
那么为什么mongoose返回验证错误,我不能null用作临时值吗?
Ric*_*sen 15
回应你的上次评论.
你是正确的,null是一个值类型,但是null类型是告诉解释器它没有值的一种方式.因此,您必须将值设置为任何非空值,否则您将收到错误.在您的情况下,将这些值设置为空字符串.即
var newUser = new user({
/* We will set the username, email and password field to null because they will be set later. */
username: '',
passwordHash: '',
email: '',
admin: false
}, { _id: false });
Run Code Online (Sandbox Code Playgroud)
小智 10
当我寻找同一问题的解决方案时,我遇到了这篇文章 - 即使值已传递到正文中,验证错误也是如此。原来我缺少 bodyParser
const bodyParser = require("body-parser")
app.use(bodyParser.urlencoded({ extended: true }));
Run Code Online (Sandbox Code Playgroud)
我最初没有包含 bodyParser,因为它应该包含在最新版本的 Express 中。添加以上两行解决了我的验证错误。
小智 6
好吧,以下方法是我摆脱错误的方法。我有以下架构:
var userSchema = new Schema({
name: {
type: String,
required: 'Please enter your name',
trim: true
},
email: {
type: String,
unique:true,
required: 'Please enter your email',
trim: true,
lowercase:true,
validate: [{ validator: value => isEmail(value), msg: 'Invalid email.' }]
},
password: {
type: String/
required: true
},
// gender: {
// type: String
// },
resetPasswordToken:String,
resetPasswordExpires:Date,
});
Run Code Online (Sandbox Code Playgroud)
我的终端向我抛出以下日志,然后在调用我的注册函数时进入无限重载:
(节点:6676)UnhandledPromiseRejectionWarning:未处理的承诺拒绝(拒绝ID:1):ValidationError:密码:
password需要路径 。,电子邮件:无效的电子邮件。(节点:6676)[DEP0018] 弃用警告:不推荐使用未处理的承诺拒绝。将来,未处理的承诺拒绝将使用非零退出代码终止 Node.js 进程。
所以,正如它所说的路径“密码”是必需的,我评论了required:true我的模型中的 validate:email行和我的模型中的行。
| 归档时间: |
|
| 查看次数: |
28916 次 |
| 最近记录: |