Home > Mobile >  MongoDB findOne async in Express.js request
MongoDB findOne async in Express.js request

Time:10-01

I just do not know what to do with a "small" problem. Probably I'm just not that far in JavaScript yet, but I'm stuck right now....

I want to retrieve values from a MongoDB and perform a calculation based on these values.

Because this happens asynchronously, I have to wait until the calculation is done, so that I can do something with the data afterwards.

But how I turn it and turn I do not come forward, I can not think of anything more. I hope someone can help me further. I have attached the code and as HTML the output of the console.

The only possible way I can think of is to create the dataset first and then do the calculation and update the whole thing, but I think there are more elegant solutions.

app.post("/api/insert/recipe", async function (req, res) {
  console.log(`/api/test/recipes: create ${req.body.title} `);

  let kcal = "0";

  console.log("start");

  await req.body.ingredients.forEach(async (element) => {
    await dbo
      .collection("ingredients")
      .findOne({
        name: element.name,
      })
      .then((result) => {
        kcal  = (result.kcal / 100) * element.amount;
        console.log("calculate");
      });
  });

  console.log("end");
});
/api/test/recipes: create test 
start
end
calculate

CodePudding user response:

forEach is not meant to be used with async await.

Try to change your code to:

app.post('/api/insert/recipe', async function (req, res) {
  let kcal = 0;

  for (const ingredient of req.body.ingredients) {
    try {
      const ing = await dbo.collection('ingredients').findOne({
        name: ingredient.name,
      });
      kcal  = (ing.kcal / 100) * ingredient.amount;
    } catch (e) {
      console.log(e);
    }
  }

  console.log(kcal);
});
  • Related