Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to pass Mongoose validation errors in Postman response

If I enter more than or less than 10 digit number in the phone number field in the postman I get the validation error message in the terminal and the server get crashes but I want to get that error message in postman JSON. how to do that?

schema.js

const { json } = require("body-parser");
const mongoose = require("mongoose");

const Schema = mongoose.Schema;

const SomeModelSchema = new Schema({
phone: {
type: Number,
required:true,
unique: true,
validate: {
  validator: (val) => {
      var re = /^\d{10}$/;
      return (!val ) || re.test(val)
  },
  message: 'Provided phone number is invalid.'
  },
},
module.exports = mongoose.model("SomeModel", SomeModelSchema);

Post method

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

router.post("/admin/add_profile", async (req, res) => {

try {
  const send = new SomeModel({ 
    phone: req.body.phone,
  });
  send.save();
 
res.json({
    responseMessage: "Everything worked as expected",
  });
} catch (error) {
  res.status(400).send(err.message);
}
});

error message in the terminal but I need to display the error message like phone number is invalid in the postman response
enter image description here

>Solution :

You should await your save() call. Otherwise the call continues to run, but it will never reach the catch-block, since the error was thrown asynchronously in your promise.

This is also the reason why your whole app crashes and does not catch this error.

This means that just using await send.save(); should resolve the issue.
After that your catch block will be processed. Unfortunately you catch errors in the variable named error, but you try to read the message from the variable named err, which still needs to be corrected.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading