我试图用mongoose在mongodb中保存一个新文档,但是ValidationError: Path 'email' is required., Path 'passwordHash' is required., Path 'username' is required.即使我提供电子邮件,passwordHash和用户名,我也能得到。
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. */ } });
那么为什么猫鼬会返回验证错误,我不能null用作临时值吗?
null
回应您的最后评论。
您正确的认为null是一个值类型,但是null类型是一种告诉解释器它 没有value的方法 。因此,必须将这些值设置为任何非空值,否则会收到错误消息。在您的情况下,请将这些值设置为空字符串。即
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 });