You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Express与Pug多页面展示文章问题:首页报错及最新文章需求

问题解决步骤

1. 修复「Cannot read properties of undefined (reading 'length')」错误

这个错误的核心原因是:你直接将article_list.pug中的代码复制到index.pug,但首页的路由没有向index模板传递article_list变量,导致Pug模板遍历的时候article_list为undefined,触发了读取length属性的错误。

解决方法是给首页路由添加文章查询逻辑,将需要的数据传递给模板:

第一步:修改首页控制器函数

在你的Express控制器中,添加(或修改)首页的处理函数,查询最新文章数据:

// 首页控制器 - 获取最新10篇文章
exports.index = function(req, res, next) {
  Article.find({}, "title author createdAt")
    .sort({ createdAt: -1 }) // 按创建时间倒序,最新文章排在最前
    .limit(10) // 限制最多10篇
    .populate("author")
    .exec(function(err, latest_articles) {
      if (err) {
        return next(err);
      }
      // 渲染首页模板,传递最新文章数据
      res.render("index", {
        title: "首页",
        latest_articles: latest_articles
      });
    });
};

注意:如果你的Article模型没有createdAt字段,需要在Schema中添加timestamps: true,MongoDB会自动为文档生成创建和更新时间。

第二步:修改index.pug模板

使用控制器传递的latest_articles变量来渲染内容,不要直接复用列表页的article_list变量:

extends layout

block content
  h1= title

  h2 最新文章
  ul
    each article in latest_articles
      li
        a(href=article.url) #{article.title}
        |  by #{article.author.name}
        |  (#{article.createdAt.toLocaleDateString()})
    else
      li 暂无最新文章

2. 实现多页面文章展示需求

「查看所有文章」页面优化

你现有的article_list控制器已经可以展示所有文章,但可以优化作者显示逻辑(不要写死Adam),修改article_list.pug:

extends layout

block content
  h1= title

  ul
    each article in article_list
      li
        a(href=article.url) #{article.title}
        |  by #{article.author.name}
    else
      li There are no articles.

首页展示最近5-10篇文章

上面的首页控制器已经通过limit(10)实现了最多10篇最新文章的查询,如果需要调整数量,直接修改limit()的参数即可(比如limit(5)取5篇)。

内容的提问来源于stack exchange,提问作者Dagger

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 12:53:17