繁体   English   中英

Mongoose 验证不记录自定义错误消息

[英]Mongoose validation doesn't log custom error message

这是我的用户 model:

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" } 如何让它记录我的自定义错误消息?

Mongoose 中的唯一性不是验证参数(如要求); 它告诉 ZCCADCDEDB567ABAE643E15DCF0974E503Z 在 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);
}
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM