Updating mongodb entries is not working all the time

Viewed 51

I want to get the entry at index gameNumber in the history collection. From that entry I want to take team1Player1 and find that player in the rating collection and then set his games to an arbitary number. This code works sometimes but idk what makes it not work

 app.post("/delete",  function (req, res) {
        var gameNumber = req.body.test;

        History.find({},  async function (err, historyRecords) {
            if (err) {
                console.log(err);
                return;
            }

             await Rating.updateOne({name: historyRecords.reverse()[gameNumber-1].team1Player1}, { games: 9999});
        })
       // res.redirect("/delete");
    });
1 Answers

Before answering your question, I want to note a few issues with your code.

  1. You are mixing callback style functions with async await (promise based). You are using await on Rating, why not do it on History as well?
  2. Your are using an expressive db which allows you to do complex queries, use it to your advantage.
  3. Due to your passing a callback, but trying to render /delete at the end, the /delete will execute before your callback is invoked due to the callbacks async nature. In order for your code to complete, you either go full callback style on everything, or promise based, or of course, async await, which is syntactic sugar on top of promises.

Lets query the db for the lists at index: index, take note that I used limit. In your example you take all of them into memory, both wasting resources + network bandwidth, always limit your queries!

Here is an example with async await:

app.post("/delete", async function (req, res, next) {
  var gameNumber = req.body.test

  const [ gameRetrieved ] = await History.find({ gameNumber }).limit(1)
  await Rating.updateOne({ name: gameRetrieved.team1Player1 }, { games: 9999 })
});

Here is an example with callbacks:

app.post("/delete", async function (req, res, next) {
  var gameNumber = req.body.test
  return History.find({ gameNumber }).limit(1).exec((err, [ gameRetrieved ]) => {
    return Rating.updateOne({ name: gameRetrieved.team1Player1 }, { games: 9999 }).exec((err, rating)=>{
      res.render('/delete')
    })
  })
});

I did not account for error handling as that is not the scope here. To sum things up: a callback/promise is async, doing anything outside of its scope will execute before/after it depending on the situation, which in your case sometimes finished before rendering delete and sometimes did not.

Related