Hi,
I have a route in node/express that takes some req.body info from a form
and objectifies it and adds it to a mongodb collection. I had it all coded
up and it was working for me both locally and when I uploaded it. This is
the code (using a promise, I believe):
router.post("/input/:id", ensureAuthenticated, async (req, res) => {
Project.findOne({
_id: req.params.id
}).then(project => {
const newInput = {
inputTitle: req.body.inputTitle,
inputValue: req.body.inputValue,
};
// Add to array - I think this was causing the issue
project.inputs.unshift(newInput);
project.save().then(project => {
res.redirect(`/projects/output/${project.id}`);
});
});
});
But then a colleague who was testing it told me that for him on every
browser except Chrome, it wasn't working - he's not a tech person so
difficult for me to ascertain the precise error, but I'm pretty sure the
problem was that the object just wasn't adding to the collection. My best
guess is that the 'project.save()' command was 'winning the race' against
the unshift command. So I changed my code to include a try/catch block and
async/await, and it worked fine for me (but it worked fine for me before).
So this is my new code:
router.post("/input/:id", ensureAuthenticated, async (req, res) => {
try {
const newInput = {
inputTitle: req.body.inputTitle,
inputValue: req.body.inputValue,
};
const project = await Project.findOne({
_id: req.params.id
});
project.inputs.unshift(newInput);
await project.save();
res.redirect(`/projects/output/${project.id}`);
} catch (e) {
res.send(e);
}
});
Sorry for the long question, but can anyone help me with this, is the
second way of doing it better, as in, more likely to ensure that the
newInput variable is actually added to the mongo collection? Is there a
difference between the two methods (with and without 'async/await') that
makes one superior to the other for my purposes?
Thanks.
--
Job board: http://jobs.nodejs.org/
New group rules:
https://gist.github.com/othiym23/9886289#file-moderation-policy-md
Old group rules:
https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines
---
You received this message because you are subscribed to the Google Groups
"nodejs" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/nodejs/9b272b73-a3ef-4291-9fc7-9845a1fc0eb5%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.