我正在尝试使用 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
作为临时值吗?
最佳答案
回应您的最后评论。
你说得对,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 });
https://stackoverflow.com/questions/31663665/