簡體   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