mongoose:validation错误path是必需的

我试图用mongoose在mongodb中保存一个新的文档,但是我得到了ValidationError: Path 'email' is required., Path 'passwordHash' is required., Path 'username' is required. 即使我提供电子邮件,passwordHash和用户名。

这是用户架构。

  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 }); 

这是我如何创build和保存用户对象。

  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会返回一个validation错误,我不能使用null作为临时值吗?

回应你最后的评论。

你是正确的,null是一个值types,但是nulltypes是告诉解释器它没有价值的一种方式。 因此,您必须将这些值设置为任何非空值,否则会出现错误。 在你的情况下将这些值设置为空string。 即

 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 });