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

120
Views
Data not returning from async function with database connection

The goal is to call a function from my main script that connects to a database, reads a document from it, stores pieces of that document in a new object, and returns that object to my main script. The problem is I cannot get it all to work together. If I try one thing, I get the results but my program locks up. If I try something else I get undefined results.

Long story short, how do I open a database and retrieve something from it to another script. The program is a quiz site and I want to return the quiz name and the questions.

const myDb = require('./app.js');

var myData = myDb.fun((myData) => {
    console.log(myData.quizName);
});

Here is the script that tries to open the database and find the data

const { MongoClient } = require("mongodb");
const {mongoClient} = require("mongodb");

const uri = connection uri goes here but my name is hard coded into it at the moment so I removed for privacy

const client = new MongoClient(uri);

const fun = async (cback) => {
  try {
    await client.connect();

    const database = client.db('Quiz-Capstone');
    const quizzes = database.collection('Quiz');

    const query = {quizName: "CIS01"};

    const options = {
      sort: {},
      projection: {}
    };

    const quiz = await quizzes.findOne(query, options);

    var quizObject = {
      quizName: quiz.quizName,
      quizQuestions: quiz.quizQuestions
    }

    //console.log(testOb);

  } finally {
    await client.close();
    cback(quizObject);
  }
}


fun().catch(console.dir);


module.exports = {
  fun: fun
}

UPDATE: Still stuck. I have read several different threads here about asynchronous calls and callbacks but I cannot get my function located in one file to return a value to the caller located in another file.

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