nhandledPromiseRejectionWarning:ValidationError:用户验证失败:password:要求路径`password`

时间:2020-08-06 11:54:13

标签: validationerror unhandled-promise-rejection

我正在尝试使用node和mongo注册用户,但出现此ValidationError:

unhandledPromiseRejectionWarning:ValidationError:用户验证失败:密码:路径password是必需的,用户名:路径username是必需的,电子邮件:路径email是必需的。

这是我的注册功能。

exports.signup =   async function (request, res, next) {

    try {
        let user =  await db.User.create(request.body);
        console.log(user);
        let { id,email,username } = user;
        let token = jwt.sign({
            id,
            email,
            username
        },
            process.env.SECRET_KEY 
        );
        return res.status(200).json({
            id,
            username,
            token
        })
    } catch (err) {
        if (err.code === 11000) {
            err.message = "sorry, username/email are token";
        }
        return next({  
            status: 400,
            message: err.message
        })
    }

这是我的用户模型

const userSchema = new mongoose.Schema({
    email: {
        type: String,
        required: true,
        unique: true,
    },
    username: {
        type: String,
        required: true,
        unique: true
    },
    password: {
        type: String,
        required: true,
    },
    profileImageUrl: {
        type: String,
    },
    messages:[{
        type:mongoose.Schema.Types.ObjectId,
        ref:'Message'
    }]
})

userSchema.pre('save', async function (next) {  
    try {
        if (!this.isModified('password')) {
            return next();
        }
        let hashedPassword = await bcrypt.hash(this.password, 10);
        this.password = hashedPassword;
        return next();
    } catch (err) {
        return next(err);
    }
});

const User = mongoose.model("user", userSchema);
module.exports = User;

注意:我正在使用Postman对此进行测试。

2 个答案:

答案 0 :(得分:0)

是的,我找到了问题。这些字段是必填字段,因此,如果您尝试使用空字段插入新用户,则会收到该错误。这些字段为空,因为“ body-parser”中间件仅处理JSON和urlencoded数据,而不处理多部分内容。所以我不得不将索引文件更改为

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

我还将Postman中的内容类型更改为“ X-www-form-urlencoded”。现在,填充了请求正文,并正确插入了用户

答案 1 :(得分:0)

我也遇到过这个错误。 在您的用户模型中,删除所有字段中的 required:true,如下所示:

email: {
    type: String,
    unique: true
}