0

hey guys l have a query and l am trying to save its data into a variable but it keeps on returning undefined everytime l call the variable. The values l am trying to save into to the variable are from the database so l can loop over them with a forEach loop on a later stage

This is my code:

var userData = db.users.find({}, function(err, data){return data})
console.log(userData);

l tried to use some of the answers from other posts with people who have encountered the same problem but l am not getting anywhere

Evans Munatsa
  • 39
  • 1
  • 7
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – wscourge Jan 23 '18 at 09:04
  • @ wscourge, what you refered me to is totaly the opposite of what l want to so because the answer is using Ajax – Evans Munatsa Jan 23 '18 at 09:09

1 Answers1

0

Using async / await (available since node -v == 7.6):

(async function() {

    const userData = await db.users.find({})
    console.log(userData);

})();

Using Promise.then()

db.users.find({})
    .toArray()
    .then(function (userData) { 
       console.log(userData) 
    })

Using callback, like you do:

db.users.find({}, function(err, data) {

    data.toArray(function(err2, userData) {

         console.log(userData);

    })

})
wscourge
  • 10,657
  • 14
  • 59
  • 80