Home > Enterprise >  Returning data from Model.find() function in mongoose
Returning data from Model.find() function in mongoose

Time:01-16

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

CodePudding user response:

With promises you can achieve it as follows

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

// using it in another function 
const result = await data();

CodePudding user response:

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);
})()
  •  Tags:  
  • Related