繁体   English   中英

当我尝试使用 mongoose“findByIdAndRemove”方法时,为什么我的 EJS 变量返回“未定义”

[英]Why is my EJS variable returning “undefined” when i'm trying to use the mongoose “findByIdAndRemove” method

我正在尝试在单击按钮时从 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 (服务器文件)中调用删除 function 的方法

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 很陌生,我已经搜索了一些答案,但似乎无法确定我所写内容的语法错误。 如果您需要更多我的代码等,请随时告诉我,提前谢谢!

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

<button>要成为一个成功的控件,它必须是用于提交表单的提交按钮

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

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


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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM