Search and add table data in form [Nodejs and Mongodb]

Asked

Viewed 54 times

0

I’m trying to load data from 3 tables into a form from routa, but it only takes the data from Municipality in the select of Country. It is supposed to have 3 selects (Country; Country; Municipality) and each bring their data. How do I do this using the code logic below?

router.get('/unidade/add', function(req, res){
        Country,City,Municipality.find().then(function(countries, cities, municipalities){
            res.render("ferramentas/addunidade", {countries: countries, cities: cities, municipalities: municipalities})
        }).catch(function(err){
            req.flash("error_msg", "Houve um erro ao carregar o formulário")
            res.redirect("/ferramentas/unidade")
        })
    })

1 answer

0


You can wait for the completion of the promises:

router.get('/unidade/add', async (req, res) => {
  try {
    const [countries, cities, municipalities] = await Promise.all([Country.find(), City.find(), Municipality.find()]);
    res.render('ferramentas/addunidade', { countries, cities, municipalities });
  } catch(e) {
    req.flash('error_msg', 'Houve um erro ao carregar o formulário');
    res.redirect('/ferramentas/unidade');
  };
});

Promise . all()

The method Promise.all(iterable) returns a single Promise that solves when all the promises in the iterable argument are resolved or when the iterable argument passed as argument does not contain promises. It is rejected on the grounds of the first promise which was rejected.


Asynchronous functions

The statement async Function defines an asynchronous function, which returns an object Asyncfunction.

You can also define asynchronous functions using a async expression Function.

When an asynchronous function is called, it returns a Promise. When the asynchronous function returns a value, a Promise will be solved with the value returned. When the asynchronous function throws an exception or some value, the Promise will be rejected with the value launched.

An asynchronous function may contain an expression await, which pauses the execution of the asynchronous function and waits for the resolution of the Promise passed, and then resumes the execution of the asynchronous function and returns the solved value.

  • Thanks for your help. But if I wanted only the states of a given country and the provinces of this state to appear, how would it look?

  • @Horapedrosa in this case you described the doubt is another. To get an answer to this question you must open another question and someone who has the knowledge necessary to answer it will instruct you

Browser other questions tagged

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