Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

285
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!