Let's say we have a mongoDB with cars, and users can add cars. The goal is to prevent more than one car with an identical license plate to be saved. Stack is node/express and mongoose.
Scenario: A car with the provided license plate DOES already exist in the db.
First attempt:
console.log('Before check')
await Car.findOne({ licensePlate }, (err, foundCar) => {
if (err) return next(err)
if (foundCar) return res.status(400).send('license plate exists already in db.')
})
console.log('After check')
// some other code, saving to db and stuff
return res.status(200).send('The car was saved succesfully.')
My naive expectation was that if i prefix moongooses findOne function with an await keyword, the code after the "await block" will not be executed because a car is found and then the request is terminated by sending a 400 response. What happens instead is that the code after the "await block" is executed which results in a
Error: Can't set headers after they are sent.
Second attempt:
console.log('Before check')
try {
const foundCar = await Car.findOne({ licensePlate })
if (foundCar) return res.status(400).send('license plate exists already in db.')
} catch (err) {
return next(err)
}
console.log('After check')
// some other code, saving to db and stuff
return res.status(200).send('The car was saved succesfully.')
This works as expected and prevents any code from exceduting after the if(foundCar) check
Question: Can someone enlighten me what happens here in attempt one? Looking at it now it does feel weird to combine a callback with an await keyword, but apperently i don't understand async/await enough to really see what's happening here. Does await in this case mean that "the code waits" only for findOne to finish and then the callback and the rest of the code run at the same time? Any pointer to useful ressources to fully understand what's going on would be very much appreciated.