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

89
Views
Async Express Router Function to MongoClient

I'm using Nodejs Express, the router middleware, in this case, MongoDB and using the POST method via JQuery ajax. Does anyone know why the router.post doesn't call, but a .get works. Does anyone know why the router.post doesn't get triggered when called as a Promise/async.

Async route here doesn't get called on ajax post.

async function asyncMain() {
  const uri = "mongodb endpoint";
  const client = new MongoClient(uri)

try {
    await client.connect().then(console.log('Connected to MongoDB'));

    //keeps awaiting cause it never executes.
    await pushToDB(client)
    //all mongoClient functions work with await here
    //Express http Post doesn't work with await here

} catch (e) {
    console.error(e);
} finally {
    await client.close();
  }
}

asyncMain().catch(console.error);

async function pushToDB(client) {
router.post('/', async(req, res, next) => {
    
    const result = await client.db('user').collection('notes').insertOne(req.body);
    console.log(`Results ${ result.insertedId }`);
  })
}

I tried using this async Middleware implementation with no results. Such as wrapping the post function's callback in asyncMiddleware to no avail.

 const asyncMiddleware = fn =>
 (req, res, next) => {
    Promise.resolve(fn(req, res, next))
        .catch(next);
 };

My working sync function for reference.

function main() {
   const uri = "mongodb endpoint";
   const client = new MongoClient(uri)

   client.connect().then(console.log('connected to DB'));
   router.post('/', (req, res) => {
    
   const result = client.db('user').collection('notes').insertOne(req.body);
   console.log(`Results ${ result.insertedId }`);
  })
}
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!