how to pass multiple database queries to a route?

Asked

Viewed 58 times

-2

Problem:

I am developing an application in Nodejs + Express and I have reached a stage where I need to pass several queries to the database by a single route.

NOTE: I use the Sequelize ORM to perform these tasks with the bank and I don’t have much knowledge with default or asynchronous functions.

below follows the code I tried to implement, but it did not work:

app.get('/monitoramento', eUsuario, (req, res) => {
    
    Bloco2.findAll({limit: 1, order: [['updatedAt', 'desc']]}) +
    Bloco1.findAll({limit: 1, order: [['updatedAt', 'desc']]}).then((bloco1, bloco2) => {
        res.render('monitoramento', {bloco1: bloco1, bloco2: bloco2})
    }).catch((err) => {
        req.flash('error_msg', 'Não foi possível listar dados.')
        res.redirect('/homepage')
    })
})

someone can help me?

1 answer

1


For you to perform two queries and then do something with the results, you can use async/await.

The results of the queries will be stored in the corresponding variables and you can make N queries, each one individually. The await is necessary to wait for the query to be completed and you can get the answer (as in .then()).

app.get('/monitoramento', eUsuario, async (req, res) => {

    const bloco2 = await Bloco2.findAll({limit: 1, order: [['updatedAt', 'desc']]});
    const bloco1 = await Bloco1.findAll({limit: 1, order: [['updatedAt', 'desc']]});

    // Faça algo com as respostas bloco1 e bloco2
});

Another option is the chaining of .then(). Below is an example of .then() nested:

app.get('/monitoramento', eUsuario, (req, res) => {

    Bloco2.findAll({limit: 1, order: [['updatedAt', 'desc']]}).then(bloco2 => {
        // Faça algo aqui com o bloco2

        Bloco1.findAll({limit: 1, order: [['updatedAt', 'desc']]}).then(bloco1 => {
            // Faça algo aqui com o bloco1 e bloco2
        });

    });;

});

Obviously the most readable solution is with async/await :)

  • thank you very much solved here!

Browser other questions tagged

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