我试图用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作为临时值吗?

推荐答案

回应你最后的 comments .

null是一种值类型,这是正确的,但是null类型是告诉解释器它有no 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 });

Mongodb相关问答推荐

MongoDB:从集合页面数据中提取不同的值

会话的Mongo-go驱动程序版本.Copy()

如何在MongoDB中查找和过滤嵌套数组

在MogoDB中按时间间隔分组、统计文档和获取间隔时间

如何对嵌套在另一个数组中的数组中的字段执行查找?

Select 筛选聚合中的嵌套字段

MongoDB Aggregate 根据时间进行多重分组

DB 中的引用对象在 GraphQL 查询中返回 null

Mongoose 更新不同类型的记录

是否可以迭代 mongo 游标两次?

将MongoDB连接到前端?

`fields cannot be identical'和''` mongoimport错误

Spring Mongo 条件查询两次相同的字段

当前的 URL 字符串解析器已弃用

TypeError: object of type 'Cursor' has no len()

Cannot connect to MongoDB errno:61

如何在第一个文档中恢复 MongoDB ChangeStream 而不仅仅是在我开始收听后更改

mongo dbname --eval 'db.collection.find()' 不起作用

如何使用 mongodb-java-driver 进行 upsert

哪个数据库适合我的应用程序 mysql 或 mongodb ?使用 Node.js 、 Backbone 、 Now.js