Home > Enterprise >  How to say custom message that the Email is unique from mongoose Schema
How to say custom message that the Email is unique from mongoose Schema

Time:05-20

How to say the custom message that the Email is unique from mongoose Schema. I do not want to check that this email exists or not from my back-end because I already said in mongoose schema that

email: {
    type: String,
    required: [true, "Please Enter your Email"],
    unique: [
      true,
      "Please use unique mail to create an account",
    ],
    validate: [validator.isEmail, "Please Enter a valid Email"],
  },

for getting this message from err. message in the console but instead of this I am getting this one : "message": "E11000 duplicate key error collection: E-COMMERS_v1_Database.users index: email_1 dup key: { email: \"[email protected]\" }",

I know what is the meaning of this message but I set my custom message in

unique: [
      true,
      "Please use unique mail to create an account",
    ],

I want to get my message from mongoose/DB. How?? Is it the correct way to set a message?

CodePudding user response:

We can solve it in regester controller or route whatever your js file from back end not from DBM. So we can write a statement in catch block :

if (e.message.includes("E11000")) {
      return res.status(500).json({
        message: "This Email Already Used try with another email",
        success: false,
      });
    }

Or we can make our own error handler function

(err,req,res,next)=>{
 if (err.message.includes("E11000")) {
          return res.status(500).json({
            message: "This Email Already Used try with another email",
            success: false,
          });
        }
}

we can use the above error handler function multi-time for various errors with a different statements like

module.exports = (err, req, res, next) => {
  err.statusCode = err.statusCode || 500;
  err.message = err.message || "Internal Server Error";
  return res.status(err.statusCode).json({
    success: false,
    error: err.stack,
  });
};
  • Related