javascript - 使用 Node JS 在 Mongodb 中创建数据
问题描述
我使用 node js 作为我的后端语言。我通过使用表单提交数据在 mongodb 中创建数据,但我想找到最新输入的数据并将其显示在我的 ejs 模板中。
这是我的代码:
/*mongoose schema setup*/
const codeSchema = new mongoose.Schema({
first: String,
second: String,
third: String,
event: String,
link: String
});
const Code = mongoose.model('Code', codeSchema);
/* GET home page. */
router.get('/welcome', async function(req, res, next) {
await Code.find({}).sort({_id: -1}).exec(function(err, data) {
if(err)
{
console.log(err);
}
else
{
//console.log(data);
res.render('index', {data: data});
}
});
});
/* GET new form form page. */
router.get('/update', function(req, res, next) {
res.render('newform');
});
/* POST update welcome page. */
router.post('/welcome', async function(req, res, next) {
const info = {
first: req.body.first,
second: req.body.second,
third: req.body.third,
event: req.body.event,
link: req.body.link
};
await Code.create(info, function(err){
if(err) {
console.log(err);
}
else {
res.redirect('/welcome');
}
});
});
代码工作正常,它创建并从我的数据库中提取最后 n 条记录,但是当我尝试在我的 html 中显示数据时,它没有显示出来。我还尝试使用 findOne() 方法,该方法实际工作并显示最后 n从我的数据库记录。当我的数据库没有数据时出现问题,findOne() 没有工作并在我的 ejs 模板中生成错误。
我使用 find({}) 方法从我的数据库中找到数据。就像我在我的 ejs 模板中做 First name - <%= data.first %> 一样,我的数据不会显示。我还检查了我的 mongo 数据库,其中包含通过表单传递的所有信息。请帮忙 !!!!!
PS - 我可以使用 for 循环显示来自 db 的所有数据,但我只想显示特定数据。
解决方案
Nithin K Joy 这里是我的 index.ejs
<h1>Index Page</h1>
<h4> Person1- <%= data.first %> <h4/>
<h4> Person2- <%= data.second %> <h4/>
<h4> Person3- <%= data.third %> <h4/>
<h4> Event name- <%= data.event %> <h4/>
<h4> Registration Link- <%= data.link %> <h4/>
这是我提交记录的表格
<form action="/welcome" method="POST" style="width: 30%; margin: 40px auto;">
<input type="text" id="winner1" name="first" placeholder="1st">
<input type="text" id="winner2" name="second" placeholder="2nd" >
<input type="text" id="winner3" name="third" placeholder="3rd" >
<input type="text" id="event" name="event" placeholder="Event Name" >
<input type="text" id="link" name="link" placeholder="Event Regestration link" >
<button type="submit class="btn btn-success btn-block">Submit</button>
如果我将 index.ejs 代码放在循环中,它可以正常工作,但我不希望 FORM 的多个输入显示在 index.ejs 中,我只想要最后一条记录
推荐阅读
- algolia - 如何简化搜索查询参数?
- java - 被底部导航视图隐藏的滚动视图最后的底部内容
- azure - powerShell Azure 函数中的 Connect-PnPOnline 出现 TokenHelper 错误
- javascript - 如何使用自定义表情符号制作反应角色?
- javascript - 当有未分阶段的更改时,如何从“npm install $anything”出错?
- java - java - 如何在Java中使用Google Analytics Data API(GA4)来扩展获取值以获取screenPageViews的计数?
- java - 什么时候在java中打开数据库连接
- kotlin - 如何访问服务中的标头?
- node.js - Node & Docker,安装 Node 模块后无法运行脚本
- linux - 如何使用 ssmtp 发送电子邮件