I am working on an express app using nodejs and mongoose, i am trying to use js function to update the number of likes on a post in database in my ejs file but it is not working , i have tried onclick() also, bascically anything inside the script tag is not running . Why is this happening , and how can i update the likes of a particular post in database by clicking a button.
Though, i have achieved this likes updation by redirecting to a route in app.js where mongoose function updateOne does it , but i want likes updated without reloadig the page on a button click
update likes route in app.js
app.get('/liked/:id', (req,res)=>{
Post.updateOne({_id: req.params.id}, {$inc: {likes:1}}, (err,likedpost)=>{
if(err) console.log(err)
else{
res.redirect("/posts/engineering");
}
})
})
show.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
// here i want to add post model of mongoose
var Post = require("../../models/post.js")
<h1> <%= post.title %> </h1>
<h3> <%= post.publish_date %> </h3>
<p> <%= post.content %></p>
<button class="likes">like</button>
</body>
<script>
console.log("like button increment"); // not printing on console
var l = document.querySelector(".likes");
l.addEventListener("click", function(){
console.log("***********");
// here i wanted to update the "likes" field of this post by 1 i.e when user clicks the like button without reloading the page
Post.updateOne({_id: post._id}, {$inc: {likes: 1}});
console.log(post.likes + "people liked" + post.title)
})
</script>
</html>