Question about handling database-queries in mongoose/mongodb properly

Question: what is the recommended way to handle a sequence of database operations where later operations are depending on the result of the former?

An example snippet for a database update:

  let short_url = -1;
  Counter.findOneAndUpdate({sequence_value:{$gt:0}}, {$inc:{sequence_value:1}}, {}, function(err, docs){
    short_url=docs.sequence_value;
    console.log(111, short_url);
  });
  console.log(222, short_url);

The result in console is:

222, -1
111, 42

Problem: the new updated value is not yet available when I make the 2nd console.log().
(I’m coming from PHP/MySQL and there it’s working different: execution will not continue until an database-operation is finished)

I found e.g. this tutorial using async/await:
https://medium.com/@Abazhenov/using-async-await-in-express-with-node-8-b8af872c0016

But I am not sure whether this is the right way

How about wrapping everything in an outer function and using async/await?

async function myFunction() {
   const blahs = await bleh.doStuff(blah => {
       console.log(blah);
       return blah;
  });
  console.log(blahs)
}
1 Like

I will try that, it sounds logic.