Mongoose’s Findone method is running in infinite loop

Asked

Viewed 72 times

0

I have the following problem. I have a Findone method to search if a user exists in the database, according to the user and password. But when I run the method - using Inuit, it ends up in an infinite loop, while I do not cancel the request.

Method code

// LOGIN - GET
    async login(req, res) {
        // Encriptando senha
        // let password = encriptacao(req.body.password)
        // console.log(password);

        // const user = await Usuario.findOne({ username: req.body.username, password: password })
        const user = await Usuario.findOne({ username: 'mateus', password: '133ed6f8476497d7a0a4239c2a68c19e' })
        console.log(user);

        if (user) {
            res.header('author', user.username)
            //res.header('logado', true)
            return res.redirect('/admin')
        } else {
            res.header('logado', false)
            return res.status(401).json({ status: 'error', cause: 'Usuário e/ou senha incorretos e/ou não existentes' }).send()
        }
    }

Output on console(do console.log(user)):

{
  _id: 5e9f8c195e983a2a4cbbb083,
  username: 'mateus',
  password: '133ed6f8476497d7a0a4239c2a68c19e',
  name: 'sousa',
  registerDate: 2020-04-22T00:13:13.792Z,
  __v: 0
}
{
  _id: 5e9f8c195e983a2a4cbbb083,
  username: 'mateus',
  password: '133ed6f8476497d7a0a4239c2a68c19e',
  name: 'sousa',
  registerDate: 2020-04-22T00:13:13.792Z,
  __v: 0
}

NOTE: There is only one user and password like this; On the console, it’s on an infinite loop, like I said

Update: I removed the res.redirect('/admin') And it worked. It’s not in infinite loop. But I don’t understand why.

2 answers

0

It is considered a good practice to have Try catch when using async await. What is happening is that very likely the method findOne is launching an Exception that is not being resolved.

Try the following code:

  async login(req, res) {
    try {
      const user = await Usuario.findOne({ username: 'mateus', password: '133ed6f8476497d7a0a4239c2a68c19e' })
      console.log(user);

      if (user) {
          res.header('author', user.username)
          //res.header('logado', true)
          return res.redirect('/admin')
      } else {
          res.header('logado', false)
          return res.status(401).json({ status: 'error', cause: 'Usuário e/ou senha incorretos e/ou não existentes' }).send()
      }
    } catch(e) {
      console.log(e.message, e.code);
      return res.status(500).json({message: e.message});
    }
  }
  • Hello, thank you very much. But unfortunately not solved :(, continues the loop...

  • What you are calling infinite loop is the page in your browser give some error like "ERROR CONNECTION TIMEDOUT" or something like the correct?

  • No, no, I use Insomnia to test the routes, so when I make the request - it will execute this method, it works, but it is in infinite loop. It only stops when I click to cancel the request

  • Insonium works on the same principle as a broser, makes an HTTP request for an endpoint, if it doesn’t have a server response your connection will be timeout. As you may have repaired the code inside the catch block only had a console.log, IE, I was only going to print the error on the console without returning you an HTTP Response. If you can see what you have on your console you can confirm that you will most likely have your Exception error there.

0

Guys, I got the problem solved. The following is, as we see, my code after checking if the user exists, it creates two headers and redirects to the route '/admin'. So, in the GET method of the admin route, it tries to read the headers, and if the "logged in" header does not exist or is false, it sends it to the login page again. And since this is another route, the header was never set. Then, it was in the loop...

Code of route "admin"

// PÁGINA ADMIN - GET
    async admin(req, res) {
        try {
            const total = await Post.count()
            const { page = 1 } = req.query
            const logado = req.headers.logado
            const author = req.headers.author
            console.log(logado + 'a');


            if (logado == true) {
                const posts = await Post.paginate({}, {
                    page,
                    limit: 10,
                    sort: {
                        'dateCreation': -1,
                    }
                })

                return res.render('admin',
                    { post: posts.docs, total, author }
                )
            }else {
                return res.redirect('/login')
            }
        } catch (error) {
            console.log(error);
            return res.redirect('/login')
        }

    },

Browser other questions tagged

You are not signed in. Login or sign up in order to post.