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

235
Views
How can I ensure that my nodejs code runs sequentially while calling Mongoose?

I have 2 database collections and I want to use the result of the first query, as input to the second query, while ensuring the whole code runs sequentially. Here's what my code looks like:

app.post("/Search", async (req, res) => {
    criteria = req.body.criteria
    c = req.body.c
    total = req.body.total
    try {
        const fquery = await db.find(criteria);
        console.log(fquery);//print 1
        let r = fquery.filter(async function (element) {
            let f = element.field;
            console.log(f);//print 2
            const squery = await db2.find({field:f});
            console.log(squery);//print 6
            let cond = squery.length == 0;//result set empty
            if (c == value) {
                cond2 = //some condition
            }
            else if (c == value2) {
                cond2 = //another condition
            }
            else {
                cond2 =//3rd condition
            }
            console.log(cond);//print 7
            console.log(cond2);//print 8
            return (cond || cond2);
        })
        console.log(fquery);//print 3
        console.log("xxxx111");//print 4
        console.log(r);//print 5
        res.json(r);

    } catch (err) {
        res.json({ message: err });
    }

});

Currently, the code works sequentially till it reaches (const squery = await db2.find({field:f});) instead of waiting for it to finish, it goes on to the logs after the filter function, in a sequence as I have commented beside each console.log. I want it to finish the filter function first, then print and send the result to the user. How can I do that?

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

0

You can pass two parameters in console log

Assign numbers to check sequence Ex. Console.log(1,"message or object");

And Use filter with a collection of promises is to use Promise.all and then apply the function to your collection of results.

Refrence link How to use Array.prototype.filter with async?

Other case

If Issue related async/await in mongodb . I mention question related async/await refrence below.

Node.js mongodb driver async/await queries

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!