Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

175
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda