Home > Mobile >  Why is there no message in mongoose error object?
Why is there no message in mongoose error object?

Time:08-25

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": "[email protected]"
}

}

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

}

CodePudding user response:

I would suggest to wrap an await/async try/catch block to your method and to check if you are getting anything from req.body before trying to save to the database:

    exports.signUp = async (req,res)=>{
      try { 
        const user=new User(req.body);
        if (!user) throw new Error("Your message ...");
        user.save();
        // res.status(201).json(user);
      } catch {
        res.status(422).json({ message: err.message ?? err });
      }
    }

CodePudding user response:

Using async/await for your case would be great.

const User=require("../models/userModels.js");
exports.signUp=(req,res)=>{
const user=new User(req.body);

try{
  const createdUser = await user.save();
  return res.status(200).json({user});
}catch(err){
   console.log(err);
   return res.status(500).send(err);
}
}
  • Related