0

I wrote a small Javascript module to get rows from a MongoDB database:

async function getAll() {
  await mongoose.connect(config.mongoURL).catch(err => { console.log(err); });
  const conn = mongoose.connection;
  conn.collection('healthdata')
    .find({}).toArray().then(result => {
      console.log('=>Docs:', result);
      return result;
   }).catch (err => {
    console.log(err);
   }).finally(() => {
    conn.close();
   });
}
exports.getAll = getAll

I get the correct display from the console ("=>Docs:"). But, when I want to get the result from the following calling function, I get the Undefined value ("Result:"):

app.get("/", async (req, res) => {
  var docs = await db.getAll().then();
  console.log("Result:", docs);
  res.render("index.html");
 });

What is missing? Wrong?

  • Does this question help you? [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call). – Take-Some-Bytes Sep 20 '21 at 23:23
  • Yes, this helped me. I completely rewrote my function, added a callback parameter and called the callback function with the result at the end of the function. – devops036 devops036 Sep 24 '21 at 13:57

3 Answers3

0

I think the console.log(Result:...) line is executing before your getAll completes.

I would wrap it inside the "then" clause:

app.get("/", async (req, res) => {
  const docsReturned = await db.getAll()
     .then(docs => {
          console.log("Result:", docs);
          res.render("index.html");
     })
     .catch(err => {
          console.error(err);
     }));
     return(docsReturned);

I also suggest adding a catch for any errors...good practices. :)

G-Force
  • 345
  • 3
  • 10
  • Thank you for responding and for the good practices. However, this doesn't solve the problem. I still get the Undefined value for the docs variable. – devops036 devops036 Sep 14 '21 at 16:12
  • the issues is that you're returning from the .then() function, a value. This returns (a resolved promise) to the parent function, which you don't have an assigned value to capture (or a nested return). I've edited my code to reflect the idea. – G-Force Sep 15 '21 at 15:00
0

you should not mix promises with async/await, so either the answer provide by G-Force but remove the await before db.getAll() or use var docs = await db.getAll(); this should solve your problem.

0

Bro if you are using mongoose follow these to get data from mongoose schema

schema.find().exec().then(result=>{

console.log(result)

}).catch(error=>{

console.log(error)

})

here all schema data in result that we console if any error come it displays in console.log(error)

Tony George
  • 116
  • 14