如何检查某人是否喜欢过某个帖子,这样他们就不会喜欢它多次?



我正在制作一个网站,您可以在其中发布帖子并喜欢它们。我添加了一个喜欢按钮,它会计算并保存数组中每个帖子的喜欢数量。但是,用户可以根据需要多次喜欢该帖子。我怎样才能使它能够将数组中的用户 id 与用户的 id 进行比较,以便只允许他们喜欢一次。

这是我的帖子模型中的类似数组

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>

这是我服务器中的 app.post.js

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方法检查数组中是否存在。

相关内容

最新更新