[英]How to check if someone has liked a post so they can't like it more than once?
我正在制作一個網站,您可以在其中發布帖子並喜歡它們。 我添加了一個點贊按鈕,它會計算並保存數組中每個帖子的點贊數量。 但是,用戶可以根據需要多次喜歡該帖子。 我怎樣才能做到這一點,以便將數組中的用戶 ID 與用戶的 ID 進行比較,以便只允許他們喜歡一次。
這是我的帖子 model 中的類似數組
likes: [{
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'users'
}
}]
這是實際的按鈕,監聽點擊
<div>
<button class = "likesButton" id = "{{this._id}}" href = "/likes/{{this._id}}"
class="btn btn-dark">likes
</button>
<span> {{ this.likes.length }} </span>
</div>
{{/each}}
{{/if}}
<script src = "https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.js"
integrity = "sha256-bd8XIKzrtyJ1O5Sh3Xp3GiuMIzWC42ZekvrMMD4GxRg=" crossorigin = "anonymous">
</script>
<script>
const likesButtons = document.querySelectorAll('.likesButton');
likesButtons.forEach( likeButton => {
likeButton.addEventListener('click', ( ) => {
axios.post(`/likes/${likeButton.id}`);
location.reload();
});
});
</script>
這是我 server.js 中的 app.post
app.post('/likes/:id', async (req, res) => {
try {
//console.log(req.params.id)
const post = await Post.findById(req.params.id);
post.likes.unshift({ user: req.user.id });
await post.save();
res.redirect('/cogfeed');
} catch (err) {
console.log(err.message);
res.status(500).send('Server Error')
}
})
您可以使用Array#includes
方法檢查數組中是否存在。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.