[英]Accepting Data From a Form And Saving It To MongoDB through Mongoose & Express
應該很簡單,但我遇到了障礙。
表格盡可能簡單。 只有一個標題字段和一個正文字段。
我希望從看起來像這樣的表單中取回一個對象:
{title:'The Title', body:'This is some body text'}
或者也許這個:
{'title':'The Title', 'body':'This is some body text'}
相反,我得到的是這樣的:
{ '”title”': 'The Title', '”body”': 'This is some body text' }
對象鍵 title 和 body 用單引號和雙引號括起來。
保存到數據庫的對象如下所示:
{ _id: new ObjectId("6182e9ed83c9bbfd6e753ac5"), __v: 0 }
換句話說,保存到數據庫的文檔只有一個 ObjectId,沒有別的。 我通過使用 Compass 檢查數據庫來檢查這一點。
然后我對我想要的對象進行了硬編碼,覆蓋了我從表單中收到的內容。 這導致這被保存在數據庫中:
{
title: 'The Title',
body: 'This is some body text',
_id: new ObjectId("6182ea6b2b5a9c8ea3324668"),
__v: 0
}
所以問題顯然是用單引號和雙引號將對象鍵括起來。 我花了一整個下午研究這個,但我被卡住了。
然后我遇到了另一個問題。 無論我多么努力,我都無法發布問題,因為我不斷收到以下消息:
您的代碼格式似乎不正確
三個小時后我放棄了。 您可以在 PDF 中找到我的代碼。 鏈接在這里:
https://drive.google.com/file/d/1ShfIKNXwEHBuxJ_uBGEf9s1jxb-DripB/view
這是非常簡單的教科書內容。 你直接到了底部,看到了快遞后編碼。
幫助!!!!!
客戶端代碼
<!DOCTYPE html>
<html lang="en">
<%-include('layouts/header');-%>
<body>
<!-- Navigation-->
<%-include('layouts/navbar');-%>
<!-- Page Header-->
<header class="masthead" style="background-image: url('assets/img/contact-bg.jpg')">
<div class="container position-relative px-4 px-lg-5">
<div class="row gx-4 gx-lg-5 justify-content-center">
<div class="col-md-10 col-lg-8 col-xl-7">
<div class="page-heading">
<h1>Create New Post</h1>
<span class="subheading">Have questions? I have answers.</span>
</div>
</div>
</div>
</div>
</header>
<!-- Main Content-->
<div>
<form action="/posts/store" method="POST">
<label>Title</label><br>
<input type="text" class="form-control" placeholder="Title" id="title" name=”title”>
<br>
<label>Body</label><br>
<textarea rows="5" id="body" name=”body” ></textarea>
<br>
<button type="submit" >Send</button>
</form>
</div>
<!-- (all formatting removed from form)--->
<!-- Footer-->
<%-include('layouts/footer');-%>
<!-- Bootstrap core JS-->
<%-include('layouts/scripts');-%>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<!-- Core theme JS-->
<script src="js/scripts.js"></script>
<!-- * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *-->
<!-- * * SB Forms JS * *-->
<!-- * * Activate your form at https://startbootstrap.com/solution/contact-forms * *-->
<!-- * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *-->
<script src="https://cdn.startbootstrap.com/sb-forms-latest.js"></script>
</body>
</html>
在這一行<input type="text" class="form-control" placeholder="Title" id="title" name=”title”>
將name=”title”
更改為name="title"
並對這一行進行操作<textarea rows="5" id="body" name=”body” ></textarea>
將name=”body”
更改為name="body"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.