简体   繁体   中英

Mongoose validation doesn't log custom error message

This is my user 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. Instead it logs 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); it tells Mongoose to create a unique index in MongoDB for that field.

The uniqueness constraint is handled entirely in the MongoDB server. When you add a document with a duplicate key, the MongoDB server will return the error that you are showing (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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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