Solucionado (ver solução)
Solucionado
(ver solução)
5
respostas

Select banco

Estou tentando aplicar o que aprendi nesse curso em projetinho meu.

Só que eu travei em uma questão.

Eu preciso que uma pagina mostre o resultado de duas tabela.

Só que eu nao consigo rodar o segundo for

/infra/CategoriaDAO.js

function CategoriaDAO(connection){
    this._connection = connection;
}

CategoriaDAO.prototype.lista = function(callback){
    this._connection.query('select * from categoria',callback);
}

CategoriaDAO.prototype.mentores = function(callback){
    this._connection.query('select * from mentor',callback);
}

module.exports = function(){
    return CategoriaDAO;
}

/routes/mentor.js
module.exports = function(app){
    app.get('/mentores',function(req,res){
        var connection = app.infra.connectionFactory();
        var CategoriaDAO = new app.infra.CategoriaDAO(connection);

        CategoriaDAO.lista(function(erros,resultados){
            res.render('mentores/mentores',{lista:resultados});
        });

        CategoriaDAO.mentores(function(erros,resultados){
            res.render('mentores/mentores',{mentores:resultados});
        });

        connection.end();
    });
};

/views/mentores.ejs

<div class="box-content col-xl-12">

                <section class="filter col-xl-12">
                    <p>Filtre por:</p>

                        <nav class="filter-choose col-xl-2">
                            <h2>Selecionar <span class="icon-down"></span></h2>
                            <ul>
                                <%for (var i = 0; i < lista.length; i++) {%>
                                <li><%=lista[i].nome%></li>
                                <%}%>
                            </ul>
                        </nav>
                </section>

                <div class="showcase-mentors col-xl-12">
                    <ul>
                        <%for (var i = 0; i < mentores.length; i++) {%>
                        <li class="col-xl-2">
                            <figure class="mentors-images">

                                <figcaption><h2><%=mentores[i].nome%></h2></figcaption>
                            </figure>
                        </li>
                        <%}%>
                    </ul>
                </div>

            </div>


ERRO MENSAGEM

ReferenceError: /Applications/XAMPP/xamppfiles/htdocs/labmentoria/src/views/mentores/mentores.ejs:40
   38| <div class="showcase-mentors col-xl-12">
   39| <ul>
>> 40| <%for (var m = 0; m < mentores.length; m++) {%>
   41| <li class="col-xl-2">
   42| <figure class="mentors-images">
   43| 

mentores is not defined
   at eval (eval at compile (/Applications/XAMPP/xamppfiles/htdocs/labmentoria/node_modules/ejs/lib/ejs.js:481:12), <anonymous>:33:27)
   at returnedFn (/Applications/XAMPP/xamppfiles/htdocs/labmentoria/node_modules/ejs/lib/ejs.js:512:17)
   at View.exports.renderFile [as engine] (/Applications/XAMPP/xamppfiles/htdocs/labmentoria/node_modules/ejs/lib/ejs.js:364:31)
   at View.render (/Applications/XAMPP/xamppfiles/htdocs/labmentoria/node_modules/express/lib/view.js:126:8)
   at tryRender (/Applications/XAMPP/xamppfiles/htdocs/labmentoria/node_modules/express/lib/application.js:639:10)
   at EventEmitter.render (/Applications/XAMPP/xamppfiles/htdocs/labmentoria/node_modules/express/lib/application.js:591:3)
   at ServerResponse.render (/Applications/XAMPP/xamppfiles/htdocs/labmentoria/node_modules/express/lib/response.js:960:7)
   at Query._callback (/Applications/XAMPP/xamppfiles/htdocs/labmentoria/src/routes/mentores.js:7:8)
   at Query.Sequence.end (/Applications/XAMPP/xamppfiles/htdocs/labmentoria/node_modules/mysql/lib/protocol/sequences/Sequence.js:86:24)
   at Query._handleFinalResultPacket (/Applications/XAMPP/xamppfiles/htdocs/labmentoria/node_modules/mysql/lib/protocol/sequences/Query.js:144:8)
   at Query.EofPacket (/Applications/XAMPP/xamppfiles/htdocs/labmentoria/node_modules/mysql/lib/protocol/sequences/Query.js:128:8)
   at Protocol._parsePacket (/Applications/XAMPP/xamppfiles/htdocs/labmentoria/node_modules/mysql/lib/protocol/Protocol.js:280:23)
   at Parser.write (/Applications/XAMPP/xamppfiles/htdocs/labmentoria/node_modules/mysql/lib/protocol/Parser.js:74:12)
   at Protocol.write (/Applications/XAMPP/xamppfiles/htdocs/labmentoria/node_modules/mysql/lib/protocol/Protocol.js:39:16)
   at Socket.<anonymous> (/Applications/XAMPP/xamppfiles/htdocs/labmentoria/node_modules/mysql/lib/Connection.js:109:28)
   at emitOne (events.js:96:13)
5 respostas

Acho que o que está acontecendo é que no primeiro render, a página já é renderizada e não dá tempo esperar a segunda query executar e por isso o mentores não está definido na view.

Duas soluções:

1 - Pra evitar duas queries, você poderia fazer um join das duas tabelas (se fizer sentido) e ai você só teria uma querie e um render pra carregar a página, isso ainda dá um bonus na performance.

2 - juntar as duas queries e usar um único render. Exemplo:

CategoriaDAO.lista(function(erros,listagem){
   CategoriaDAO.mentores(function(erros,mentores){
    res.render('mentores/mentores',{lista:lentagem, mentores:mentores});
   }
});

Acredito que a segunda opção funcione (testa pra mim?) e é a mais fácil neste caso, mas eu gosto mais da primeira.

Espero ter ajudado, bons estudos!

A segunda opção não funciono.

Vou mudar o banco.

Obrigado pela ajuda.

Não funcionou? deu algum erro?

solução!

Eu resolveria seguindo a sugestão da segunda opção.

Tente fazer da seguinte forma:


module.exports = function(app){
    app.get('/mentores',function(req,res){
        var connection = app.infra.connectionFactory();
        var CategoriaDAO = new app.infra.CategoriaDAO(connection);

        var resultadoCategoria = {};
        var resultadoMentor = {};

        CategoriaDAO.lista(function(erros,resultados){
            if (erros){
                console.log(erros);
                res.send(erros);
                return;
            }
            resultadoCategoria = resultados;
        });

        CategoriaDAO.mentores(function(erros,resultados){
            if (erros){
                console.log(erros);
                res.send(erros);
                return;
            }
           resultadoMentor = resultados;
        });

        res.render('mentores/mentores',{lista:resultadoCategoria, mentores:resultadoMentor});    
        connection.end();
    });
};

Obrigado pela ajuda!!!

Usei a segunda opção :)

Quer mergulhar em tecnologia e aprendizagem?

Receba a newsletter que o nosso CEO escreve pessoalmente, com insights do mercado de trabalho, ciência e desenvolvimento de software