3
I have the following structure in the following tables.
partner (idParceiro, name, email, phone) example partnerTag (idPartner, tag)
What I need to do, a select in the partner table and do a for in the result and query the partner table by idParty and bring the results to fill in a Json that stays that way.
[{
nome: 'nome teste',
email: 'email teste',
telefone: 1199999999,
tags: ['tag1', 'tag2', 'tag3']
}, {
nome: 'nome teste',
email: 'email teste',
telefone: 1199999999,
tags: ['tag1', 'tag2', 'tag3']
}]
The problem is that when I consult the first table and do a go in the result to get the ID and go in the other table it gets lost by being async.
How can I resolve this in NODE.JS because I have several queries that depend on another to generate a Json.
Follow my code below.
router.route('/parceiro').get(function(req, res) {
parceiro.consultar(req, function(err, rows){
if(err) return res.status(400).json(err);
var p = [];
_.each(rows, function(one) {
var pa = {};
pa.parceiroId = one.parceiroId;
pa.clienteId = one.clienteId;
pa.nome = one.nome;
pa.imagemDestaque = one.imagemDestaque;
pa.imagemLogo = one.imagemLogo;
pa.desconto = one.desconto;
pa.titulo = one.titulo;
pa.descricao = one.descricao;
pa.urlSite = one.urlSite;
pa.validadeDe = one.validadeDe;
pa.validadeAte = one.validadeAte;
pa.isCupom = one.isCupom;
pa.urlOferta = one.urlOferta;
pa.cupomDesconto = one.cupomDesconto;
pa.ativo = one.ativo;
pa.dataCadastro = one.dataCadastro;
pa.tags = [];
parceiro.tag(req, function(err, r){
_.each(r, function(two) {
pa.tags.push(two.tag);
});
});
pa.categorias = [];
pa.regioes = [];
p.push(pa);
});
return res.status(200).json(p);
});
});
Please put the code in text and not image. The logic of
res.status
must be insideparceiro.tag()
, and then wait for that answer/callback. But you couldn’t do it in one SELECT with a JOIN?– Sergio
Not in a single select because I have a partner can have 100 tags and categories and regions although they will be in the formed {idRegiao:1, name:'region name'}.
– Daniel Metta
Wouldn’t it be cleaner
var pa = one;
? instead of passing the properties one by one?– Sergio
one is from the partner table that does not have the tags properties, categories and regions, only if they can be included later.
– Daniel Metta
Okay, and you want the same for the regions, and categories like
parceiro.tag
?– Sergio
Yes I have that for and inside I want to consult the 3 tables separately, the problem is only that when it enters the partner method.tag() the value is inside and I can’t play for the pa.tags.push().
– Daniel Metta
I understand the problem and see the mistake. I ask to better hit the answer.
– Sergio
The table is called
tag
ortags
? you have the property astags
but the tabletag
? and the others?– Sergio
I left an answer, this is bedtime. I’ll take a look tomorrow to see if you understood the logic and if it helped you. (Or if you found a bug :P )
– Sergio