简体   繁体   English

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

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

This is my user model:这是我的用户 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 }
);

and here I create the user在这里我创建用户

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);
  }
};

At first I validate the password and username.首先我验证密码和用户名。 I have set custom messages for them, but when the user is not unique it does not log The username is taken as I have written in the validation.我已经为他们设置了自定义消息,但是当用户不是唯一的时,它不会记录The username is taken正如我在验证中所写的那样。 Instead it logs E11000 duplicate key error collection: DB.users index: username_1 dup key: { username: "User56" } .相反,它记录E11000 duplicate key error collection: DB.users index: username_1 dup key: { username: "User56" } How can I make it log my custom error message?如何让它记录我的自定义错误消息?

Uniqueness in Mongoose is not a validation parameter (like required); Mongoose 中的唯一性不是验证参数(如要求); it tells Mongoose to create a unique index in MongoDB for that field.它告诉 ZCCADCDEDB567ABAE643E15DCF0974E503Z 在 MongoDB 中为该字段创建一个唯一索引。

The uniqueness constraint is handled entirely in the MongoDB server.唯一性约束完全在 MongoDB 服务器中处理。 When you add a document with a duplicate key, the MongoDB server will return the error that you are showing (E11000...).当您添加具有重复键的文档时,MongoDB 服务器将返回您正在显示的错误 (E11000...)。

You have to handle these errors yourself if you want to create custom error messages.如果要创建自定义错误消息,您必须自己处理这些错误。 The https://mongoosejs.com/docs/middleware.html#error-handling-middleware ("Error Handling Middleware") provides you with an example of how to create custom error handling: 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