在路由中表达传递值以使用 ejs 查看

Express pass values in route to view with ejs

这是我的 post 路线:

// CRUD posts.
app.post('/crud', function(req, res) {
  db.users.addPost(req.body);
  res.redirect('crud')
});

这是我的获取路线:

app.get('/crud', function(req, res) {
  res.render('crud', {
    user: req.user,
    posts: db.users.retrievePost()
  });
});

这是我用来从数据库中检索 posts 的函数:

// Retrieve posts from database to pass to view.
exports.retrievePost = function() {
  var cursor = postsCollection.find().toArray(function(err, record) {
    console.log(record);
    return record;
  });
}

当我登录记录时,它returns以下数据:

[ 
  { _id: 57cb835ba8b8250bdcd65e5d, userCreate: 'This is a question' },
  { _id: 57cb85709435720c055b10e6, userCreate: 'hello' },
  { _id: 57cb87b10dc3ec0c3a78f970, userCreate: 'hello' },
  { _id: 57cb87c20dc3ec0c3a78f971, userCreate: 'what up here' } 
]

这就是我使用 ejs 在 'crud' 视图中显示 userCreate 值的方式。

<ul class="posts">
  <% for(var i=0; i<posts.length; i++) { %>
  <li class="post">
    <span><%= posts[i].userCreate %></span>
  </li>
  <% } %>
</ul>

错误是: 无法读取未定义的 属性 'length'。

为什么 posts 是未定义的?在我呈现视图时的 get 路由中,我将 retrievePost() 的值分配给 posts。然后,我从呈现的视图调用 posts。我们可以假设该函数已正确导出,因为我在同一路由文件中使用了同一文件中的其他函数。这里有什么问题?

我想补充一点 post 我测试通过的事实

title : "testing"

并且能够通过以下方式呈现它:

<%= title %>

所以我真的不确定为什么 posts 不起作用。

正如我在评论中所述:问题是传递给 res.renderposts 的值未定义。 postsCollection.find() 不会返回,并且该值在任何情况下都不会传回。您需要 retrievePost 也接受回调(或使用 promises 等)。

这是所需行为的非常基本的实现。

app.get('/crud', function(req, res) {
    // call passing in a callback
    db.users.retrievePost(function(err,result) {
        // call render inside this call back, after result has been retrieved
        res.render('crud', {user: req, user, posts: result});
    })
});

// Retrieve posts from database to pass to view.

exports.retrievePost = function(callback) {
   var cursor = postsCollection.find().toArray(function(err, record) {
      console.log(record);
      // naively just invokes the passed callback
      // you could also do error handling or other processing
      // here as well, before passing back the result through the callback
      callback(err,record);
   });
}

它将是:

locals.posts.length()

而不是

posts.length