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

Mongoose中Post.find({})返回undefined,Express社交应用问题求助

问题原因及修复方案

1. 直接报错的核心原因:登录后渲染allPosts页面未传递posts参数

你在index.js的登录成功逻辑中,直接调用res.render("allPosts")但没有查询帖子数据,也没有传递posts变量,模板拿到的posts自然是undefined,触发遍历时报长度读取错误。

2. 新创建帖子不展示的原因:异步操作执行顺序错误

addNewPost.js中aPost.save()是异步IO操作,你没有等待保存完成就直接执行Post.find()查询,此时新帖子还没写入数据库,查询结果自然不包含最新数据。

3. 潜在隐患:未处理Mongoose操作的错误

所有查询/保存操作都没有捕获处理错误,如果数据库操作抛出异常,posts变量也会是undefined。

具体修复代码

修复index.js登录逻辑

登录成功后先查询全量帖子再渲染页面:

/* index.js 登录成功部分修改 */
const Post = require("../models/post") // 顶部先引入Post模型
// ...
if (bcrypt.compareSync(password, account.password)) {
  req.session.email = account.email
  req.session.userLoggedIn = true
  // 新增查询帖子逻辑
  Post.find({}).exec(function(err, posts) {
    if (err) posts = []
    res.render("allPosts", {title: "All Posts", posts: posts})
  })
}

修复addNewPost.js的保存逻辑

把帖子查询放到save的回调函数中,确保保存完成后再查询:

/* addNewPost.js post路由部分修改 */
aPost.save(function(err) {
  if (err) {
    console.log(err)
    return res.render("addNewPost", {title: "Social Application", error: "帖子保存失败"})
  }
  console.log("Post saved successfully !")
  // 保存成功后再查询帖子
  Post.find({}).exec(function(err, posts) {
    if (err) posts = []
    res.render("allPosts", {title: "All posts", posts: posts})
  })
})
// 删掉原来放在save外面的Post.find逻辑

修复allPosts.js的错误处理

增加错误兜底,保证即使查询失败也会传递空数组给模板:

/* allPosts.js 路由修改 */
router.get('/', function(req, res, next) {
    Post.find({}).exec(function(err, posts) {
        if (err) {
          console.log(err)
          posts = []
        }
        res.render("allPosts", {title: "Social Application", posts: posts})
    })
})

可选优化:allPosts.pug判断逻辑优化

把undefined判断替换为长度判断,兼容空数组场景:

if !posts || posts.length === 0
    h1 No posts to show here 
else 
    each post in posts
        // 原有渲染逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 15:06:05