I’m facing an issue where my API returns undefined even though the database query runs successfully.
API responds with
undefinedor empty objectNo error is thrown
Console logs inside the database query show correct data
Response is sent before the data is available
app.get("/api/user/:id", (req, res) => { let user; User.findById(req.params.id) .then((data) => { console.log("Fetched user:", data); user = data; }) .catch((err) => { console.error(err); }); res.json(user); });i have tried
Console logging inside
.then()(data exists)Wrapping code in
try/catchRestarting the server
Why does
userbecomeundefinedin the response even though the database query returns correct data, and what is the correct way to handle this in Express?