Search code examples
javascriptnode.jsmongoose

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


Solution

  • With promises you can achieve it as follows

    const data = () => {
        return MyModel.find({});   
    }
    
    // using it in another function 
    const result = await data();