改善猫鼬验证错误处理 [英] Improve mongoose validation error handling

查看:96
本文介绍了改善猫鼬验证错误处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下具有所需验证的架构:

I have the following schema with required validations:

var mongoose = require("mongoose");
var validator = require("validator");

var userSchema = new mongoose.Schema(
  {
    email: {
      type: String,
      required: [true, "Email is a required field"],
      trim: true,
      lowercase: true,
      unique: true,
      validate(value) {
        if (!validator.isEmail(value)) {
          throw new Error("Please enter a valid E-mail!");
        }
      },
    },
    password: {
      type: String,
      required: [true, "Password is a required field"],
      validate(value) {
        if (!validator.isLength(value, { min: 6, max: 1000 })) {
          throw Error("Length of the password should be between 6-1000");
        }

        if (value.toLowerCase().includes("password")) {
          throw Error(
            'The password should not contain the keyword "password"!'
          );
        }
      },
    },
  },
  {
    timestamps: true,
  }
);

var User = mongoose.model('User', userSchema);

我通过以下方式发送发帖请求,从而通过表格传递电子邮件和密码:

I pass the email and password through a form by sending post request using the following route:

router.post("/user", async (req, res) => {
  try {
    var user = new User(req.body);
    await user.save();
    res.status(200).send(user);
  } catch (error) {
    res.status(400).send(error);
  }
});

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

每当我输入一个违反验证规则的字段时,都会收到一条很长的错误消息,这很明显。但是现在,我想改进错误处理,以便为用户轻松解释。而不是重定向到通用错误页面,如何重定向到相同的注册页面,并在显示错误的错误字段附近显示Flash消息?同样,如果成功,也应该执行类似的操作,例如在顶部显示绿色的闪烁消息。

Whenever I enter a field against the validation rules, I get a very long error message, which is obvious. But now, I want to improve the error handling so that it gets easy to interpret for the users. Rather than redirecting to a generic error page, how can I redirect to the same signup page and display the flash messages near the incorrect fields telling about the error? And also on success, something similar should be done, like a green flash message on the top.

我在注册页面上使用了ejs。

I am using ejs for my signup pages.

推荐答案

在catch块中,您可以检查错误是否为猫鼬验证错误,并动态创建一个错误对象,如下所示:

In the catch block, you can check if the error is a mongoose validation error, and dynamically create an error object like this:

router.post("/user", async (req, res) => {
  try {
    var user = new User(req.body);
    await user.save();
    res.status(200).send(user);
  } catch (error) {
    if (error.name === "ValidationError") {
      let errors = {};

      Object.keys(error.errors).forEach((key) => {
        errors[key] = error.errors[key].message;
      });

      return res.status(400).send(errors);
    }
    res.status(500).send("Something went wrong");
  }
});

当我们发送这样的请求正文时:

When we send a request body like this:

{
   "email": "test",
   "password": "abc"
}

响应将为:

{
    "email": "Please enter a valid E-mail!",
    "password": "Length of the password should be between 6-1000"
}

这篇关于改善猫鼬验证错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆