[英]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.