【问题标题】:Limiting votes for users with mongodb使用 mongodb 限制用户的投票
【发布时间】:2021-06-28 09:06:02
【问题描述】:

我创建了一个非常简单的论坛,用户可以在其中注册、登录和发帖。我正在尝试实现一个用户可以喜欢帖子的功能,但我很难得到它,所以用户只能喜欢每个帖子一次。到目前为止,我已经有了它,因此用户可以单击“Like”,它会将帖子文档的“likeCount”字段增加 1。

我一直在尝试做的是创建一个单独的模型来跟踪喜欢,它将获取用户的电子邮件和他们喜欢的帖子的 id,并检查电子邮件和 id 是否存在于“投票”收藏。如果它们确实存在,则拒绝用户。我一直在尝试使用 collection.find() 函数来做到这一点,但我一定做错了,因为我遇到了很多麻烦。任何帮助将不胜感激

forum.ejs 文件中的点赞按钮:

<form action="/forum/<%= newPost.id %>/like?_method=POST" method="POST" class="d-inline">
    <button type="submit" class="btn btn-danger">Like</button>
</form>

投票代码:

router.post('/forum/:id/like/', async (req,res) =>{ //like post
    const likePost = await Createpost.findById(req.params.id)

    let voteInfo = new Vote({
        voteEmail: req.user.email,
        votePost: likePost.id,
    });

    if (Vote.find(req.user.email && likePost.id)){
        req.flash('error_msg', 'You already voted!')
        res.redirect ('/forum')
    }
    else{
    Createpost.updateOne({_id: likePost}, {$inc: {likeCount:1}}, 
        function (err, user){
        if (err) return next(err);
        User.findById(req.user._id, function(err, user) {
            if (err) return next(err)
            voteInfo = voteInfo.save()
            req.flash('success_msg', 'Post liked!')
            return res.redirect('/forum'), {
            }
        });
            })
        }
})

【问题讨论】:

    标签: javascript node.js mongodb express


    【解决方案1】:

    您查询投票模型的方式存在问题

    let votes = await Vote.find({ voteEmail: req.user.email ,  votePost : likePost.id});
    if(votes.length>0){
    
    
    }
    

    Mongoose.find()

    【讨论】:

    • 建议您在执行 likePost.id 之类的操作之前保留 null 检查,除非您绝对确定 likePost 是否不为 null。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多