首页 > 解决方案 > 如何让我的快速应用程序从 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('/');
});

标签: javascriptnode.jsmongodbexpressejs

解决方案


推荐阅读