Is it a scope problem?

Asked

Viewed 22 times

0

I have a problem in obtaining the value of a variable in Nodejs.

router.post('/admin/categorias/nova', (req, res) => {

  var erro = [];

  Categoria.findOne({
    slug: req.body.slug
  }).then((categorias) => {
    if (categorias) {
      erro.push({texto: "Slug Existente tente uma nova"});
    }
  }).catch((err) => {
    console.log('Erro na verificação de Slugs existentes: ' + err);
  });

  if (erro.length > 0) {
    res.render('admin/addcategorias', {erro: erro});
  } else {};
});

As you can see, both the error variable, and the query function in the database, "Category.findOne", are within a route. I declare the variable outside of the Category function, fill it inside the function, only after, check it on a conditional. Inside the function it returns length = 1 (when it enters the condition), but outside the function it continues with value 0. What can be?

  • Asynchronous JS, maybe this is your problem, when you try to use the variable off the route, it has not yet had its set value.

  • Take a look at the questions I marked as duplicates. In practice yours if (erro.length > 0) { must be inside the .then(

No answers

Browser other questions tagged

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