0

Hey this should be very simple for you nodejs gods, I am trying to make authentication system with nodejs using mongoose so the server is successfully receiving the email and parameters entered in the front-end but it seems as if somewhere in my in my logic I am not doing everything properly can I please get some assistance in handling this error because what happens when I console log on the back-end I get the following.

User Successfully Found
EMAIL:  test1@gmail.com
PASSWORD:  test1
SIGNINUSER: undefined

I get that User Successfully found even when I entered a wrong user

**Interesting part is when I remove the .then I get back the user object but return errors with regards to unhandled promise

Code below where I am handling the signing in of users

router.post("/signin", async (request, response) => {
  const signinUser = await User.find({
    email: request.body.email,
    password: request.body.password,
  })
    .then((response) => {
      console.log("User Successfully Found");
    })
    .catch((error) => {
      console.log("User Does not exist");
    });
  
  //Here I was trying to check if I really am receiving the data from the client
  //Just to find that I am receiving the clients data
  console.log("EMAIL: ", request.body.email);
  console.log("PASSWORD: ", request.body.password);

  //Here I was trying to check if the usersInfo is being set inside the siginUser variable 
  //just to find that I getting the value of undefined
  console.log("SIGNINUSER: ", signinUser);

  if (signinUser) {
    response.status(200).json({
      _id: signinUser.id,
      name: signinUser.name,
      email: signinUser.email,
      isAdmin: signinUser.isAdmin,
      token: getToken(user),
    });
  } else {
    response.status(401).send({ message: "Invalid Email or Password" });
  }
});
Ntshembo
  • 73
  • 2
  • 7

2 Answers2

0

Without running the code I would say you are mixing await with then and monoogose queries. So in the proposed solution User.find() returns the query (which is not a promise but a theneable), you exec it to get a promise and await for result. Removing then but keeping your code behavior might look like.

router.post("/signin", async (request, response) => {
    const signinUser = await User.find({
        email: request.body.email,
        password: request.body.password,
    }).exec();
    if (!signinUser) {
        console.log("User Does not exist");
        return response.status(401).send({ message: "Invalid Email or Password" });
    }
    console.log("User Successfully Found");
    console.log("EMAIL: ", request.body.email);
    console.log("PASSWORD: ", request.body.password);
    console.log("SIGNINUSER: ", signinUser);
    return response.status(200).json({
        _id: signinUser.id,
        name: signinUser.name,
        email: signinUser.email,
        isAdmin: signinUser.isAdm
        token: getToken(user),
    });
});

I hope it helps.

More info here Mongoose - What does the exec function do?

brbn
  • 71
  • 4
  • I just tried this but I get this Error ```UnhandledPromiseRejectionWarning: ReferenceError: user is not defined``` ```UnhandledPromiseRejectionWarning: Unhandled promise rejection.``` – Ntshembo Sep 11 '20 at 22:53
  • ```UnhandledPromiseRejectionWarning: Error: Expected "payload" to be a plain object. at validate (/home/junior/Web-Projects/OnlineStore/server/node_modules/jsonwebtoken/sign.js:40:11)``` – Ntshembo Sep 11 '20 at 22:59
  • Ok! First one. Where do you define user variable? Or is just a typo? About the second one. It seems you have getToken wrapping jsonwebtoken library and passing an invalid value to it. I'm guessing the full singinuser from mongo, which is not a plain object. mongo object accepts .toObject() method to turn into a plain object. Something like getToken(signinUser.toObject()) – brbn Sep 11 '20 at 23:25
  • The user was a typo and as for the convention of the mongo object I get the following error ```signinUser[0]._id.toObject is not a function``` – Ntshembo Sep 11 '20 at 23:41
  • The [0] is giving me access to the 0th object because the server is bring something like this [{}] so for some reason I had to access the object by index so the is no mistake in the 0 – Ntshembo Sep 11 '20 at 23:42
  • It is giving you an array of objects because User.find() returns an array of document objects. Use User.findOne() instead. – brbn Sep 11 '20 at 23:47
0

Just change your response Code i think this problem will be Gone

    return response.status(200).json({
    _id: signinUser.id,
    name: signinUser.name,
    email: signinUser.email,
    isAdmin: signinUser.isAdm,
    token: getToken(user.toObject()),
});

I changed Only

token: getToken(user.toObject()),