So i'm trying to make real-time comments but the comments keep repeating and filling the page with text. How do I stop that from happening.
My Client-Side Code
Show Route
<%- include("../partials/header") %>
<h1><%- video.title %></h1>
<div><%- video.file %></div>
<p><%- video.description %></p>
<% if(auth){ %>
<% if(auth.username === "Puffier_Fisher"){ %>
<button class="btn btn-success"><a href="/videos/<%= video._id %>/edit" class="text-white">EDIT</a></button>
<form action="/videos/<%= video._id %>?_method=delete" method="post">
<button type="submit" class="btn btn-danger">DELETE!</button>
</form>
<% } else {} %>
<% } %>
<button class="btn btn-primary"><a href="/videos/<%= video._id %>/comments/new" class="text-white">New Comment</a></button><br>
<div id="comments"></div>
<script>
function findComments() {
$.ajax({
dataType:"json",
url: "/videos/<%= video._id %>/comments",
type: "GET",
success: function(res){
res.forEach(comment => {
$("#comments").append(`<strong>${comment.author}</strong>`, "<br>");
$("#comments").append(`<p>${comment.text}</p>`);
});
}
});
}
findComments();
setInterval(findComments, 5000);
</script>
<%- include("../partials/footer") %>
My AJAX Route
router.get("/videos/:id/comments", function(req, res){
Video.findById(req.params.id).populate("comments").exec(function (err, foundVideo) {
if (err) {
console.log(err)
} else {
let doc = JSON.stringify(foundVideo.comments);
res.send(doc)
}
});
});