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

181
Views
How to call MongoDB CRUD operations from outside of the async run function | JS

The following code is the default async run function for the MongoDB JS driver.

async function run() {
  try {
    await client.connect();
    const database = client.db('sample_mflix');
    const movies = database.collection('movies');
    // Query for a movie that has the title 'Back to the Future'
    const query = { title: 'Back to the Future' };
    const movie = await movies.findOne(query);
    console.log(movie);
  } finally {
    // Ensures that the client will close when you finish/error
    await client.close();
  }
}
run().catch(console.dir);

Is there any way on earth to do the CRUD operations etc outside of that function, e.g in an expressjs endpoint?

Thanks.

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

0

You can have a function that connects to the DB, probably in a different file and export the function

// DB.js
async function connectToDatabase() {
  try {
    await client.connect();
    return client.db('sample_mflix');
  } catch(err) {
    console.dir(err);
  } finally {
    await client.close();
  }
}

Then import it if you're using the export method, or just call the function

app.get('/api/path', () => {
  const db = await connectToDatabse();

  if (db) {
    const query = {
      title: 'Back to the Future'
    };

    const movie = await db.collection('movies').findOne(query);
    console.log(movie)
  }
})
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!