[英]Why are likes not being updated on button click in my mongoose schema?
我正在使用 nodejs 和 mongoose 開發一個快速應用程序,我正在嘗試使用 js 函數來更新我的 ejs 文件中數據庫中帖子的贊數,但它不起作用,我也嘗試過 onclick(),基本上任何東西里面的腳本標簽沒有運行。 為什么會發生這種情況,以及如何通過單擊按鈕更新數據庫中特定帖子的喜歡。
雖然,我已經通過重定向到 app.js 中的路由來實現此喜歡更新,其中 mongoose 函數 updateOne 執行此操作,但我希望喜歡更新而無需單擊按鈕重新加載頁面
更新喜歡 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");
}
})
})
顯示.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>
如果你想在不重新加載的情況下更新,你需要使用 AJAX 請求。
您不需要在顯示頁面中包含 post.js (var Post = require("../../models/post.js")),讓像往常一樣的路由由快遞服務器處理。
在前端/客戶端代碼中,最后將 script 標簽移到 body 標簽內。
<body>
// here i want to add post model of mongoose
<h1> <%= post.title %> </h1>
<h3> <%= post.publish_date %> </h3>
<p> <%= post.content %></p>
<button class="likes">like</button>
<script>
console.log("like button increment"); // Will print to browser console
var l = document.querySelector(".likes");
l.addEventListener("click", function(){
console.log("***********");
// MAKE AN AJAX REQUEST (POST) HERE TO localhost//liked/:id (pass the appropriate id)
// or replace localhost with actual host/domain
// Check the status returned by the POST request made on the server, if OK, update the
//like value using event listener
})
</script>
</body>
正如我在評論中提到的,向類似路由 localhost//liked/:id 發出 AJAX 請求(POST)(傳遞適當的 id)或將 localhost 替換為實際的主機/域。
檢查服務器上發出的 POST 請求返回的狀態,如果正常,則使用事件偵聽器更新類似值。
在快遞之類的路由中,如果數據庫部分成功,只需發送 200 OK 狀態,不要重定向或其他任何內容。
在 express 中,將 like 路由從 .get 更改為 .post,這很重要。
查看 AJAX 示例或教程以發出 AJAX 請求。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.