skip to Main Content

the below is my controller function

exports.validateUsername = async (uName) => {
  console.log("inside validate username");
  await User.findOne({ username: "sab2" }).then(function (err, user) {
    if (err) {
      console.log("inside err");
      console.log("error");
      console.log(err);     
      return true;
    } else {
      console.log("inside user found");
      console.log("user");
      console.log(user);
      return false;
    }
  });
};

I have record in my "user" collection with username ="sab2". But still , the promise function results in err, and goes inside if(err).

But when I do console.log(err) I get the actual user data "sab2" object.

I have a doubt if the function syntax is function(data,err).

Error object printed

enter image description here

Please suggest a solution.

2

Answers


  1. then do not return error. Do something like this to catch error

    await User.findOne({ username: "sab2" }).then((user) => {
        console.log(user)
      }).catch(error=>console.log(error))
    

    or use callback. See here

    Login or Signup to reply.
  2. The then() on a findOne does not return a error, I would rewrite like this:

      User.findOne({ username: "sab2" }, function(err, user) {
        if (err) {
          console.log("inside err");
          console.log("error");
          console.log(err);     
        return true;
        } else {
          console.log("inside user found");
          console.log("user");
          console.log(user);
        return false;
    }
      });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search