Click here to Skip to main content
15,868,164 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have a route in Node/express that is meant to add an object from a req.body form submission to a mongodb collection (using mongoose). My code was working fine for me both locally and online, but then a colleague told me that when he tested it, it was only working in google chrome, not the other browsers, and that the page would just 'flash', and nothing was added.

My best guess is that the object adding to the collection is sometimes 'losing the race' before the collection is saved and the programme moves on.

What I have tried:

Originally my code just included a promise:

JavaScript
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
       
     project.inputs.unshift(newInput);
        
     project.save().then(project => {
       res.redirect(`/projects/output/${project.id}`);
     });
   });
 });


I then altered it to include a try/catch block and an async/await:

JavaScript
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);
      }
  });


I'm not too hot on async/await etc, and I'm quite nervous about putting this app into production with it being a gamble whether the object is added to the array or not. Is the second method superior? It is 'awaiting', but I'm not sure if it's any improvement on the first method.

If anyone could help me out I'd be very grateful, I just need to ensure that the object is actually added to the collection (the 'project.inputs.unshift(newInput)' line), or that it throws an error, if it must.

Thank you.
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900