【问题标题】:Mongoose validation doesn't log custom error messageMongoose 验证不记录自定义错误消息
【发布时间】:2021-08-11 00:56:52
【问题描述】:

这是我的用户模型:

const userSchema = new Schema(
  {
    username: {
      type: String,
      required: [true, "Please enter a username"],
      unique: [true, "The username is taken"],
    },
    password: {
      type: String,
      required: [true, "Please enter a password"],
      minLength: [8, "The minimum password length is 8"],
    },
  },
  { timestamps: true }
);

我在这里创建用户

exports.create_user = async (req, res, next) => {
  try {
    const { username, password } = req.body;
    await User.validate({ username: username, password: password });
    const salt = await bcrypt.genSalt();
    const hashedPassword = await bcrypt.hash(password, salt);
    await User.create({ username: username, password: hashedPassword })
  } catch (err) {
    console.log(err.message);
  }
};

首先我验证密码和用户名。我已经为他们设置了自定义消息,但是当用户不是唯一的时,它不会像我在验证中所写的那样记录The username is taken。相反,它记录E11000 duplicate key error collection: DB.users index: username_1 dup key: { username: "User56" }。如何让它记录我的自定义错误消息?

【问题讨论】:

    标签: javascript database mongodb express mongoose


    【解决方案1】:

    Mongoose 中的唯一性不是验证参数(如要求);它告诉 Mongoose 在 MongoDB 中为该字段创建一个唯一索引。

    唯一性约束完全在 MongoDB 服务器中处理。当您添加具有重复键的文档时,MongoDB 服务器将返回您正在显示的错误 (E11000...)。

    如果您想创建自定义错误消息,您必须自己处理这些错误。 https://mongoosejs.com/docs/middleware.html#error-handling-middleware(“错误处理中间件”)为您提供了如何创建自定义错误处理的示例:

    emailVerificationTokenSchema.post('save', function(error, doc, next) {
    if (error.name === 'MongoError' && error.code === 11000) {
    next(new Error('email must be unique'));
    } else {
    next(error);
    }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-18
      • 2016-12-04
      • 1970-01-01
      • 1970-01-01
      • 2021-02-24
      • 2016-12-21
      • 2017-09-10
      • 1970-01-01
      相关资源
      最近更新 更多