javascript - 如何让我的快速应用程序从 mongodb 服务器刷新数据而无需刷新页面?
问题描述
我无法让博客帖子显示在我的快速博客应用程序的主页上...它们被保存(使用 mongo shell 确认),但是在我单击保存撰写的帖子后会发生什么是应用程序将重定向到一个空的主页(默认顶部材料除外)。也就是说,我刚刚撰写的帖子的简短版本在我手动刷新页面之前不会出现。
我的代码:
mongoose.connect('mongodb://localhost:27017/blogDB', {
useNewUrlParser: true,
useUnifiedTopology: true
});
const postSchema = new mongoose.Schema({
title: {
type: String,
required: [true, 'missing blog post title']
},
content: {
type: String,
required: [true, 'missing blog post content']
}
});
const Post = mongoose.model('Post', postSchema);
app.get('/', (req, res) => {
Post.find({}, (err, returnedItems) => {
if (!err) res.render('home', { homeStartingContent, returnedItems });
});
});
app.post('/compose', (req, res) => {
const post = new Post({
title: req.body.postTitle,
content: req.body.postBody
});
post.save();
res.redirect('/');
});
/* ----------------------------------------------------------- */
<%- include('partials/header'); %>
<h1>Home</h1>
<p><%= homeStartingContent %></p>
<% returnedItems.map(post => { %>
<h1><%= post.title %></h1>
<p>
<%= `${post.content.substr(0, 100)} ...` %>
<a href="<%= `/posts/${post.title}` %>">Read More</a>
</p>
<% }); %> <%- include('partials/footer'); %>
当我控制台记录从我的数据库返回的数组长度时 - 在 post.save() 之后 - 长度为零。所以,我不确定为什么会这样。它可能与异步代码有关,但我之前编写了另一个应用程序,它使用了与此处看到的相同类型的代码,没有问题。
编辑:我使用以下语法通过 async-await 修复了这个问题:
app.post('/compose', async(req, res) => {
const post = new Post({
title: req.body.postTitle,
content: req.body.postBody
});
await post.save();
res.redirect('/');
});
解决方案
推荐阅读
- c# - 为什么应用程序不使用我的连接字符串?
- c - 如何在 C 语言中集成语音到字符串检测器
- javascript - 为什么在像减法这样的简单计算之后我会得到像 (5.0306980803327406e-17) 这样的数字?
- python - 转换 struct_time 最后给我“.%fZ”而不是时区和微秒
- mysql - 计数和求和条件大于某事
- python-3.x - BeautifulSoup4 - 在两个不同的标签之间连接多个 html 元素
- linux - 在 NGINX 上通过 HTTP/HTTPS 拒绝所有非 443 或 80 端口的连接
- html - 如何让我的 flexbox 页脚占据底部的整个空间?
- r - 二元运算符的非数字参数
- spring-security - 带有令牌中继的 Spring Cloud Security:响应具有空集 cookie 标头