猫鼬:需要验证错误路径 [英] Mongoose: validation error path is required
问题描述
我试图用mongoose在mongodb中保存一个新文档,但是即使提供电子邮件,passwordHash和用户名,我也得到了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. */
}
});
为什么猫鼬会返回验证错误,我不能使用null
作为临时值吗?
So why does mongoose return a validation error, can I not use null
as temporary value?
推荐答案
针对您的最后评论.
您正确的认为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 });
这篇关于猫鼬:需要验证错误路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!