javascript - Mongoose:需要验证错误路径

我正在尝试使用 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/

相关文章:

mongodb - 更新 mongodb 中的嵌套文档

python - 我可以只获取 Cursor 对象(pymongo)中的第一项吗?

javascript - Meteor Collection 文档 ID : Random. id(

node.js - 聊天项目 - 使用 socket.io 进行负载平衡

node.js - Mongoose,查找,返回特定属性

mongodb - MongoDB批量FindAndModify的解决方案

java - 指定字段对于 MongoDB 是 transient 的,但对于 RestContro

mongodb - 当父字段未知时,在嵌套文档中查找具有字段的记录

node.js - 将数据插入 MongoDB - 没有错误,没有插入

python - django 和 mongodb 是否使迁移成为过去?