I have tried a lot and didn't get anything that works good for me. I tried with promise.all and setting the array globally, but with no success.
I want to search in three collections on MongoDB and when the find matches, set an object with the infos and push to an array. At the end, send a response with the objects array.
router.post('/certificado', (req, res) => {
let cpf = splita(req.body.cpf)
let array = []
function pesquisaProjeto(cpf) {
return new Promise(function (fulfill, reject) {
ProjetoSchema.find({'integrantes.cpf':cpf}, 'integrantes.$ nomeProjeto -_id',(err, usr) => {
if (err) return reject(err)
fulfill(usr)
});
})
}
function pesquisaAvaliador(cpf) {
return new Promise(function (fulfill, reject) {
avaliadorSchema.find({'cpf':cpf}, 'nome -_id',(err, usr) => {
if (err) return reject(err)
fulfill(usr)
})
})
}
function pesquisaParticipante(cpf) {
return new Promise(function (fulfill, reject) {
participanteSchema.find({'cpf':cpf}, 'nome eventos -_id', (err, usr) => {
if (err) return reject(err)
fulfill(usr)
})
})
}
pesquisaProjeto(cpf)
.then(usr => {
let participante = ({
tipo: usr[0].integrantes[0].tipo,
nome: usr[0].integrantes[0].nome
})
array.push(participante)
console.log(participante)
})
.catch(err => console.log("Não encontrou nada nos projetos. " + err.message))
pesquisaAvaliador(cpf)
.then(usr => {
let participante = {
tipo: "Avaliador",
nome: usr[0].nome
}
array.push(participante)
console.log(array)
})
.catch(err => console.log("Não encontrou nada nos avaliadores. " + err.message))
pesquisaParticipante(cpf)
.then(usr => {
let participante = ({
tipo: "Participante",
nome: usr[0].nome,
eventos: usr[0].eventos
})
array.push(participante)
console.log(array)
})
.catch(err => console.log("Não encontrou nada nos participantes dos eventos. " + err.message))
**Anything like res.send(array) that I was tired to try**
});
Sorry for the stupid doubt, but I've spent so much time trying to find the solution that I decided to resort to the community.
Thanks!
promise.allwork?res.send(array)at the.then()ofpromise.allnothing is sended to front. Think that could be some wrong with the push inside the promise and the array declaration.Promise.all.