Javascript Mongoose:需要验证错误路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31663665/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mongoose: validation error path is required
提问by 2trill2spill
I'm trying to save a new document in mongodb with mongoose, but I am getting ValidationError: Path 'email' is required., Path 'passwordHash' is required., Path 'username' is required.
even though I am supplying email, passwordHash and username.
我正在尝试使用 mongoose 在 mongodb 中保存一个新文档,但ValidationError: Path 'email' is required., Path 'passwordHash' is required., Path 'username' is required.
即使我提供了电子邮件、passwordHash 和用户名,我也收到了。
Here is the user schema.
这是用户架构。
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
});
This is how I am creating and saving the user object.
这就是我创建和保存用户对象的方式。
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. */
}
});
So why does mongoose return a validation error, can I not use null
as temporary value?
那么为什么猫鼬会返回验证错误,我可以不用null
作临时值吗?
采纳答案by Richard Christensen
In response to your last comment.
回应你最后的评论。
You are correct that null is a value type, but null types are a way of telling the interpreter that it has no value. therefore, you must set the values to any non-null value or you get the error. in your case set those values to empty Strings. i.e.
您是正确的, null 是一种值类型,但 null 类型是告诉解释器它没有 value 的一种方式。因此,您必须将值设置为任何非空值,否则会出现错误。在您的情况下,将这些值设置为空字符串。IE
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 });
回答by Parikshit Hooda
Well, the following way is how I got rid of the errors. I had the following schema:
好吧,以下方法是我摆脱错误的方法。我有以下架构:
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,
});
and my terminal throw me the following log and then went into infinite reload on calling my register function:
我的终端向我抛出以下日志,然后在调用我的注册函数时进入无限重载:
(node:6676) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): ValidationError: password: Path
password
is required., email: Invalid email.(node:6676) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
(节点:6676)UnhandledPromiseRejectionWarning:未处理的承诺拒绝(拒绝ID:1):ValidationError:密码:
password
需要路径 。,电子邮件:无效的电子邮件。(节点:6676)[DEP0018] 弃用警告:不推荐使用未处理的承诺拒绝。将来,未处理的承诺拒绝将使用非零退出代码终止 Node.js 进程。
So, as it said Path 'password' is required, I commented the required:true
line out of my model and validate:email
line out of my model.
所以,正如它所说的路径“密码”是必需的,我评论了required:true
我的模型之外的 validate:email
行和我的模型之外的行。
回答by Blondish
I came across this post when I was looking for resolution for the same problem - validation error even though values were passed into the body. Turns out that I was missing the bodyParser
当我正在寻找相同问题的解决方案时,我遇到了这篇文章 - 即使将值传递到正文中,也会出现验证错误。原来我错过了 bodyParser
const bodyParser = require("body-parser")
app.use(bodyParser.urlencoded({ extended: true }));
I did not initially include the bodyParser as it was supposed to be included with the latest version of express. Adding above 2 lines resolved my validation errors.
我最初没有包含 bodyParser,因为它应该包含在最新版本的 express 中。添加以上 2 行解决了我的验证错误。
回答by Jakarea Parvez
To solve this type of error
解决此类错误
ValidationError: Path 'email' is required.
your email is set required in Schema, But no value is given or email field is not added on model.
您的电子邮件在架构中设置为必需,但未提供任何值或未在模型上添加电子邮件字段。
If your email value may be empty set default value in model or set allow("") in validatior. like
如果您的电子邮件值可能为空,请在模型中设置默认值或在验证器中设置 allow("")。喜欢
schemas: {
notificationSender: Joi.object().keys({
email: Joi.string().max(50).allow('')
})
}
I think will solve this kind of problem.
我认为会解决这类问题。