Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Not able to compare username in database with that entered by the client

So I am trying to create a basic authentication app without using any modules or auth strategies. Just by pushing user credentials to a MongoDb database and then by comparing the entered credentials every time a user tries to login with the existing ones.

text

For some reason i am not able to filter out the mongodb document with the same username entered by the user. When i try to log it to the console i am getting a query , i am expecting an object so that both the req.body.password and user.password can be compared.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The User.findOne function returns a Query object, which represents the pending query operation. To retrieve the actual user document, you need to execute the query using .exec().

You can modify your function in this way:

app.post("/api/v1/login", (req, res) => {
  User.findOne({ username: req.body.username })
    .exec()
    .then((user) => {
      console.log(req.body.username);
      console.log(user);
      if (user) {
        const result = req.body.password === user.password;
        if (result) {
          res.redirect("/api/v1/dashboard");
        } else {
          res.status(404).json({ error: "entered password doesn't match" });
        }
      } else {
        res.redirect("/api/v1/register");
      }
    })
    .catch((error) => {
      console.log(error);
      res.status(500).json({ error: "An error occurred" });
    });
});

Let me know, If still the issue persist.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading