我正在尝试使用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
});
这是我创建和保存用户对象的方式 .
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
作为临时值吗?
2 回答
回应你的上次评论 .
你是正确的,null是一个值类型,但是null类型是告诉解释器它没有值的一种方式 . 因此,您必须将值设置为任何非空值,否则您将收到错误 . 在您的情况下,将这些值设置为空字符串 . 即
那么,以下方法是我如何摆脱错误 . 我有以下架构:
并且我的终端抛出以下日志,然后在调用我的寄存器函数时进入无限重载:
所以,正如它说Path 'password'是必需的,我评论了我的模型中的
required:true
行和我模型中的validate:email
行 .