skip to Main Content

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?

2

Answers


  1. Chosen as BEST ANSWER

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

  2. const signUp = async(req, res, next) => {
      const findOneEmail = await User.findOne({ email: req.body.email })
      if (findOneEmail) {
        return next(AppError("This email already used")); 
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search