验证错误mongodb即使在以正确的格式传递json之后

hrirmatl  于 2022-11-03  发布在  Go
关注(0)|答案(1)|浏览(139)

代码guyz有什么问题。每当我用json传递post请求时,验证错误-“需要路径confirmPassword“会在控制台中记录。我也使用了body-parser和express。json(),但它对我不起作用。

const Loginschema = mongoose.Schema({
    name : {
        type : String,
        required : [true , 'please enter your name'],
    },
    email : {
        type : String,
        required : [true ,' please enter your email'],
        unique : true,
    },
    password : {
        type : String,
        required : true
    },
    confirmPassword : {
        type : String,
        required : true,
        validate : {
            validator(value){
                return value === this.password;
            }
        }
    }
})

// -----------------------> HASHING PASSWORD <--------------------

Loginschema.pre('save' , async function (request , response , next) {
    if(!this.isModified('password')) return next();
    this.password = await bcrypt.hash(this.password , 10);
    this.confirmPassword = undefined;
    next();
})

这里是我使用的中间件

app.use(express.json());
app.use(express.urlencoded({extended: true}));

这是我在控制台上得到的错误

properties: {
        validator: [Function (anonymous)],
        message: 'Path `confirmPassword` is required.',
        type: 'required',
        path: 'confirmPassword',
        value: undefined
      },
      kind: 'required',
      path: 'confirmPassword',
      value: undefined,
      reason: undefined,
      [Symbol(mongoose:validatorError)]: true
    }
  },
  _message: 'loginData validation failed'
}
uqxowvwt

uqxowvwt1#

const Loginschema = mongoose.Schema({
    name : {
        type : String,
        required : [true , 'please enter your name'],
    },
    email : {
        type : String,
        required : [true ,' please enter your email'],
        unique : true,
    },
    password : {
        type : String,
        required : true
    },
    confirmPassword : {
        type : String,
        required : true,
        validate : {
            validator: function (value) {
                return value === this.password;
            }
        }
    }
})

validator是一个属性。官方文档

相关问题