【问题标题】:Changing a Mongodb Parameter Value Onclick更改 Mongodb 参数值 Onclick
【发布时间】:2025-11-23 11:00:02
【问题描述】:

我想为我的网站中的帖子制作一个报告按钮,在我的帖子模型中我有:reported: ,默认值为 false,我希望如果有人单击该按钮,则该值将更改为 true。

我在html页面上的ejs:

<% posts.forEach(function(post){ %>
        <% if(post.uploadedBy == Tuser){ %>
            <div class="jumbotron jumbotron-fluid">
                <div class="container">
                    <h4 class="display-4" style="text-transform: capitalize;"><%= post.title %></h4>
                    <h5><%= post.uploadedBy %></h5>
                    <p class="lead"><%= post.text %></p>
                    <a href="#" onclick="reported(<%= post %>)">Report Post</a>
                </div>
            </div>
        <% } %>
    <% }) %>

我对 app.js 文件中页面的 GET:

//get someone else's blog
router.get('/othersblog/:username',(req,res) => {
    Post.find({},(err,posts) => {
        if(err){
            console.log(err);
        }else{           
            res.render('othersblog',{
                headline: "Website | User Blog",
                title: "Blog",
                Tuser: req.params.username,
                posts: posts,
            });
        }
    })
});

如果你知道怎么做,请帮助我。谢谢。

【问题讨论】:

  • 我更新了我的答案。希望它对您有所帮助,或者让您了解如何实现目标。
  • 非常感谢它的工作!

标签: jquery node.js ajax ejs


【解决方案1】:

您可以做的是为每个post创建一条获取路线。
在您的 forEach 循环中使用此链接

<a href="/posts/report/<%= post._id %>" >Report Post</a>

这是你的路线。

router.get('/posts/report/:id',(req,res) => {
    Post.findById(req.params.id, (err,post) => {
        if(err){
            // handle error here
        }else{  
            // Here you can do what you want.
            // You can update post object.
            post.reported = true;
            post.save((error, updatedPost) => {
               // run code here.
               // You can redirect to the previous page with all posts
               // or do anything else you want.
            });      
        }
    })
});

【讨论】:

  • 我将所有帖子渲染为帖子,然后使用 foreach 浏览它们,每个帖子都有一个报告选项,所以我可以渲染正确的帖子吗?
  • 我不确定你想做什么。 report 是做什么的?提供一些额外的信息。
  • 我有用户模型和帖子模型,在我写的帖子中有一个报告默认设置为false,如果点击链接,帖子的报告将变为true,并且帖子将显示在显示已报告帖子的管理员页面中。一切都设置好了,但报告按钮
  • 因此,通过单击每个按钮,您要更新 mongodb 中的 post.reported 属性。如果我理解得很好,通过单击按钮,您必须发出帖子请求以更改该值