首页 文章

Mongoose:需要验证错误路径

提问于
浏览
15

我正在尝试使用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 作为临时值吗?

2 回答

  • 14

    回应你的上次评论 .

    你是正确的,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 });
    
  • 2

    那么,以下方法是我如何摆脱错误 . 我有以下架构:

    var userSchema = new Schema({
        name: {
            type: String,
            required: 'Please enter your name',
            trim: true
        },
        email: {
            type: String,
            unique:true,
            required: 'Please enter your email',
            trim: true,
            lowercase:true,
            validate: [{ validator: value => isEmail(value), msg: 'Invalid email.' }]
        },
        password: {
            type: String/
            required: true
        },
        // gender: {
        //     type: String
        // },
        resetPasswordToken:String,
        resetPasswordExpires:Date,
    });
    

    并且我的终端抛出以下日志,然后在调用我的寄存器函数时进入无限重载:

    (node:6676)UnhandledPromiseRejectionWarning:未处理的承诺拒绝(拒绝ID:1):ValidationError:密码:需要路径密码 . ,电子邮件:电子邮件无效 . (节点:6676)[DEP0018]弃用警告:不推荐使用未处理的拒绝承诺 . 将来,未处理的承诺拒绝将使用非零退出代码终止Node.js进程 .

    所以,正如它说Path 'password'是必需的,我评论了我的模型中的 required:true 行和我模型中的 validate:email 行 .

相关问题