Problem with Nodejs

Hi everyone. I’m working on creating a social media application using NodeJs, Mongodb, HTML , CSS etc.
The problem I’m encountering is around the ‘comments’ section, where people add comments to a post; to be specific, when a user posts a comment, the page just keeps loading until it crashes. So to avoid this, I’ve just redirected the user to the home page as soon as they add a comment to a particular post. See the code below.

app.post('/do-comment', function(req, res){
    db.collection('posts').updateOne({ "_id": ObjectId(req.body.post_id)}, {
      $push: {
        "comments": {name: req.body.name, comment: req.body.comment}
      }
    }, function(err, post){
      res.redirect('/')
    })
  })

Now, this is bad user experience. **I want the user to just see their comment appear below the post without redirecting them anywhere. **
Kindly asking for help.

Below is the code that takes the user to a particular post to make a comment:

app.get('/created-posts/:id', (req, res) => {
    db.collection('posts').findOne({ "_id": ObjectId(req.params.id)}, function (err, post){
      if (err) return console.log(err)
      res.render('single-post.ejs', {post:post})
    })
  })

Then below is the code that adds the comment to the database:

  app.post('/do-comment', function(req, res){
    db.collection('posts').updateOne({ "_id": ObjectId(req.body.post_id)}, {
      $push: {
        "comments": {name: req.body.name, comment: req.body.comment}
      }
    }, function(err, post){
      res.redirect('/')
    })
  })

Below is the HTML form (ejs template) that submits the comment:

<form id="comment-form" action="/do-comment" method="POST">
                 <input type="hidden" class="name-input" name="post_id" value="<%= post._id %>">
                 <input id="comment-name" class="name-input" placeholder="Alias Name" name="name" required>
                 <textarea id="comment-body" class="comment-body-input" placeholder="Leave a comment" name="comment" required></textarea>
                 <input type="submit" value="Comment" id="comment-submit" />
             </form> 

Welcome, csibanda.

I suspect you should event.preventDefault() for the form action. The default action for a form on submit, if I remember correctly, is to refresh the page. I also wonder if this is further a problem with the app callbacks not being treated asynchronously.

Hope this helps

Thanks Sky, let me give that a try

Sorry Sky, could you please let me know what I should send as the response. I want to avoid redirecting the user to the home page.
Looking at the code snippet below, what should I change it to?

 function(err, post){
      res.redirect('/')
    })

The whole thing is as shown below:

  app.post('/do-comment', function(req, res){
    db.collection('posts').updateOne({ "_id": ObjectId(req.body.post_id)}, {
      $push: {
        "comments": {name: req.body.name, comment: req.body.comment}
      }
    }, function(err, post){
      res.redirect('/')
    })
  })

If you don’t want to refresh the page, instead of redirect you should send back the post and process it on the frontend (append to page).
Something like this:

res.json({post})

And then on the frontend you’ll get the post.

1 Like

A lazy option would be:

function(err, post){
      res.redirect('back')
    })

The reason for the long load, before the page/server erroring out is because the app.post('/do-comment') function is not resolving to anything.

For your use case, you might be better off not using the form action attribute at all, and instead write a onclick for the input (should actually change this to a button:

<form> /* No action attribute */
  /* Usual stuff */
  <button onclick='() => {const data=document.querySelector('#comment-name').value; fetch('/do-comment', {postData: data})}'>Submit</button>
</form>

I hope this helps

1 Like

Thanks very much Sky020. It’s working as expected now.