Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

178
Visualizações
Count the number of documents with mongoose (then also use that info)

So Ive seen a lot of similar questions about counting database entries and I have figured out how to use callback functions to console.log the number, but because of the local scope of that callback I cant figure out how to actually USE that number in another function. I would like to make a random number generator for between 0 and the number of documents in my database. This is what I have so far.

 Comic.countDocuments({}, function (err, count) {
    if (err){
        console.log(err)
    }else{
        console.log(count)
    }
}); 

I would love for it to work like this but it doesnt. Whenever I do it num ends up being a huge amount of metadata instead of a number. Any ideas?

 let num = Comic.countDocuments({}, function (err, count) {
    if (err){
        console.log(err)
    }else{
        return count
    }
});

console.log(Math.floor(Math.random() * num))
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

There is no way to return data from async function, because it's async in nature. You can read this answer on SO to better understand how async calls work.

But you can simply it a bit by using async/await

const randomFunction = async() => 
{
  let num = await Comic.countDocuments({});
  console.log(Math.floor(Math.random() * num));
}

Then you can call randomFunction(); wherever you want (as long as it's exported, if using in separate file).

This will console.log the random number

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda