Before answering your question, I want to note a few issues with your code.
- 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?
- Your are using an expressive db which allows you to do complex queries, use it to your advantage.
- 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.