I have a HTML form where data is submitted to mongoDB using express and mongoose. After submitting data to mongoDB, client is shown up with the table containing all the records which is be done by redirecting to new page where all the records are shown.
Both ways are similar but later doesn’t show last (current) entry.
Way 1 (works perfectly fine):
app.post("/", (res, req) => {
const item = new Item(req.body);
item.save();
res.redirect("/results");
});
app.get("/results", (res, req) => {
Item.find({}, (err, foundResult) => {
res.render("table.html", {data:foundResult});
});
});
Way 2 (doesn’t show latest entry):
app.post("/", (res, req) => {
const item = new Item(req.body);
item.save();
Item.find({}, (err, foundResult) => {
res.render("table.html", {data:foundResult});
});
});
Way 2 shows all the data from database except the current entry.
How the code behaves normal when passed through res.redirect() and abnormal when ditto same code is executed without res.redirect()?
CodePudding user response:
In your 2nd version, you do NOT wait for item.save()
to finish before you immediately do Item.find({})
, thus it probably has not yet completed and is not included in your immediate query.
You could do this instead to both wait for item.save()
to complete, but also to log and handle errors:
app.post("/", (res, req) => {
const item = new Item(req.body);
item.save((err) => {
if (err) {
console.log(err);
return res.sendStatus(500);
}
Item.find({}, (err, foundResult) => {
if (err) {
console.log(err);
return res.sendStatus(500):
}
res.render("table.html", {data:foundResult});
});
});