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

214
Views
Can't get result from a nodejs module

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?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

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. :)

about 4 years ago · Juan Pablo Isaza Report

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.

about 4 years ago · Juan Pablo Isaza Report

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)

about 4 years ago · Juan Pablo Isaza 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!