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>