Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

235
Views
Why is there no message in mongoose error object?

I am making a user signup API, where name and email are set to be unique. When I send a JSON object which has a the same email address as an existing user, it gives an error as expected. But there is no message in that error, which i can then use to give a more usable message.

Below is the error object that i'm getting.

{ "index": 0,    
 "code": 11000,
 "keyPattern": {
    "email": 1
},
 "keyValue": {
    "email": "pranatkarode@rocketmail.com"
 }
}

And this is my controller module,

const User=require("../models/userModels.js");
exports.signUp=(req,res)=>{
const user=new User(req.body);
user.save((err,user)=>{
    if(err){
        res.send(err)
    }
    else{
        res.json({
            user
        })
    }
})
}
about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Mongoose's default error object is designed for non limited use cases. So you need to look at it and depending on what it contains add custom messages. For this specific use case of yours, you can for example do it like so:

const User = require("../models/userModels.js");
exports.signUp = async (req, res) => {
  try {
    const user = new User(req.body);
    await user.save();
    res.json({
      user,
    });
  } catch (err) {
    if (err.code === 11000 && err?.keyPattern.hasOwnProperty("email")) {
      err.message = "This email is alrady used.";
    } else if (err.code === 11000 && err?.keyPattern.hasOwnProperty("name")) {
      err.message = "This name is alrady taken.";
    }
    res.send(err);
  }
};

I'm using async/await syntax here to have a better looking code, yours would work as well.

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!