skip to Main Content

My Collection.save() function is working fine and identifying duplicate key values. But, when duplicate values occur , I am not able to get the entire error message as response.

My User.save function

const user = new User({
          first_name,
          last_name,
          email,
          username,
          password: cryptedPassword,
          bYear,
          bDay,
          bMonth,
          gender,
        }).save(function (err, data) {
          if (data) {
            console.log("inside save then data");
            return res.status(200).send(data);
          } else {
            console.log("inside save then err");
            return res.status(200).send(err);
          }
        });

My console message

(if I remove the else part

enter image description here

But when I try to send the err message as response json, I get only the below response in my postman

{
    "index": 0,
    "code": 11000,
    "keyPattern": {
        "email": 1
    },
    "keyValue": {
        "email": "[email protected]"
    }
}

How to get the full error message, so that i can intimate the duplicate key issue.

2

Answers


  1. First, I recommend using async/await. In catch, you can check if the error is a duplicate key error or not, and you can create custom error messages. Also, return statusCode 400 instead of 200.

    const user = new User({
      first_name,
      last_name,
      email,
      username,
      password: cryptedPassword,
      bYear,
      bDay,
      bMonth,
      gender,
    });
    
    try {
      await user.save();
    } catch (err) {
      if (err.code === 11000) {
        // handle error
      }
    }
    
    Login or Signup to reply.
  2. According to mongoose docs, when an error is throw, you can check for the msg property.

    Below is a full example

    const user = new User({
              first_name,
              last_name,
              email,
              username,
              password: cryptedPassword,
              bYear,
              bDay,
              bMonth,
              gender,
            })
    
    return user.save(function (err, data) {
              if (err) {
                console.log("inside save then err");
                return res.status(500).send(err.msg);
            });
    
                console.log("inside save then data");
                return res.status(200).send(data);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search