【问题标题】:Why is my EJS variable returning "undefined" when i'm trying to use the mongoose "findByIdAndRemove" method当我尝试使用猫鼬“findByIdAndRemove”方法时,为什么我的 EJS 变量返回“未定义”
【发布时间】:2021-05-26 22:03:51
【问题描述】:

我正在尝试在单击按钮时从 mongoDB 数据库中删除记录。但是当我控制台记录此按钮的值时,它返回“未定义”

下面是ejs文件

<%- include("partials/header") -%>

<h1>Home</h1>

<!-- A variable for the homepage that is populated by a body of text passed from app.js -->
<p><%= homeText %> </p>

<a class= "btn btn-primary" href="/compose" role="button">Compose a new post</a>

<%# A forEach method with a function holding a parameter of "post" which represents an element in an array, then displaying the element's title and content. %>
<% homeContent.forEach(function(post){ %>
<h1><%= post.title %></h1>
<!-- Displays only the first 100 characters of a post as well as a "read more" hyperlink which directs to a "post" page containing the full content of the post. -->
<p><%= post.content.substring(0, 100) + " ... " %> <a href="/post/<%=post._id %>">Read more</a></p>

<form action = "/delete", method="Post">
  <button type="button" class ="btn btn-link" name = "deleteButton" value = "<%=post._id%>" onClick="this.form.submit()"  ><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-trash" viewBox="0 0 16 16">
  <path d="M5.5 5.5A.5.5 0 0 1 6 6v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5zm2.5 0a.5.5 0 0 1 .5.5v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5zm3 .5a.5.5 0 0 0-1 0v6a.5.5 0 0 0 1 0V6z"/>
  <path fill-rule="evenodd" d="M14.5 3a1 1 0 0 1-1 1H13v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V4h-.5a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1H6a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1h3.5a1 1 0 0 1 1 1v1zM4.118 4L4 4.059V13a1 1 0 0 0 1 1h6a1 1 0 0 0 1-1V4.059L11.882 4H4.118zM2.5 3V2h11v1h-11z"/>
</svg> </button>   %>

  </form>


<%});%>



<%- include("partials/footer") -%>

这是我试图在我的 app.js(服务器文件)中调用删除函数的方法

app.post("/delete", function(req,res){
  const selectedId = req.body.deleteButton;

  Post.findByIdAndRemove(selectedId, function(err){
    if(!err){
      console.log(selectedId);
      res.redirect("/");
    }
  })
});

当我在控制台记录 ID 变量时,很明显它没有从 EJS 文件中正确访问帖子的 ID,因为它返回“未定义”,因此没有任何内容被删除。我在这里有什么明显的遗漏吗?我对 MongoDB 和 NodeJS 还很陌生,我四处寻找一些答案,但似乎无法确定我所写内容的语法错误。如果您需要更多我的代码等,请随时告诉我,提前谢谢!

【问题讨论】:

  • 尝试console.log(req.body, req.query) 以确保您在服务器上获得了一些数据。如果没有,你会使用一些身体解析器吗?哪一个?同样在您点击按钮之前打开 devtools 并确保属性 &lt;button ... value = "&lt;here&gt;" onClick... 中有正确的值

标签: javascript node.js mongodb mongoose ejs


【解决方案1】:

当您提交表单时,提交的数据中只会包含成功的控件。

要使&lt;button&gt; 成为成功的控件,它必须是用于提交表单的提交按钮

您的按钮不是提交按钮(您说的是type="button"),也不是(直接)用于提交表单(您正在使用 JavaScript)。

因此,您的表单中没有个成功的控件,因此 POST 请求中不包含任何表单数据。


  • 删除使用 JavaScript 提交表单的 onclick 属性
  • 删除阻止按钮成为提交按钮的type 属性

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-25
    • 2019-10-27
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 2021-03-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多