Home > Mobile >  MongoDb findOne query results in error - even if data is found
MongoDb findOne query results in error - even if data is found

Time:06-15

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.

CodePudding user response:

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

CodePudding user response:

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

  • Related