Mongoose:需要验证错误路径 [英] Mongoose: validation error path is required
问题描述
我正在尝试使用 mongoose 在 mongodb 中保存一个新文档,但我收到 ValidationError: Path 'email' is required., Path 'passwordHash' is required., Path 'username' is required.
即使我提供的是电子邮件、密码哈希和用户名.
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.
这是用户架构.
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. */
}
});
那么为什么 mongoose 会返回验证错误,我可以不使用 null
作为临时值吗?
So why does mongoose return a validation error, can I not use null
as temporary value?
推荐答案
回应您的最后一条评论.
In response to your last comment.
您认为 null 是一种值类型是正确的,但 null 类型是一种告诉解释器它没有值的方式.因此,您必须将值设置为任何非空值,否则会出现错误.在您的情况下,将这些值设置为空字符串.即
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.
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 });
这篇关于Mongoose:需要验证错误路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!