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

289
Vistas
Returning data from Model.find() function in mongoose

first off I'd like to make clear that I'm new to node.js and this may sound like a silly question but, how am I supposed to return data out of model.find() function in mongoose ( eg. with a var.exports = var )?<

const data = () =>
{
    MyModel.find().then(function(result){
        console.log(result);
        return(result);
    });
}

exports.data = data

Being the query asyncronous I'm not able to retrieve these data until the function is completed (so never). Is there anyway to return these informations in a variable eg:

const retriever = require('../utils/test.js') //calling the exports file


test = retriever.data
console.log(test)

Thank you very much in advance

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

With promises you can achieve it as follows

const data = () => {
    return MyModel.find({});   
}

// using it in another function 
const result = await data();
over 4 years ago · Santiago Trujillo Denunciar

0

1.You can use a callback, as below

const data = (callback) =>
{
    MyModel.find().then(function(result){
        console.log(result);
        //return(result);
        callback(results);//we pass in a function which will be used to pull out 
        //data
    });
}

exports.data = data

// THE AREA WHERE THIS CODE IS USED

const {data} = require('./to/data')

//show data 
 data(function (result) {
 console.log( result );// data from callback
 })

2. using async/await promies

const data = async () =>
{
   let results = await MyModel.find();
}
exports.data = data

ON USING THIS FUNCTION

const {data} = require('./to/data')

(async function () {
    let res = await data();
    console.log(res);
})()
over 4 years ago · Santiago Trujillo 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