Mongoose向Topic的posts数组push Post时出现undefined错误
解决帖子回复push到主题时的
Cannot read properties of undefined (reading 'push')错误 问题根源
你代码里的Topic.findById(topicId)是异步操作,直接赋值给topic变量时,它只是一个未兑现的Promise对象,并非实际从数据库查询到的Topic文档,所以topic.posts会是undefined,调用push就会触发报错。另外你的Topic Schema里的posts字段定义也有可优化的地方。
修复步骤
1. 修正Topic Schema的posts字段定义
把原来的数组类型改成mongoose推荐的引用数组格式,确保能正确关联Post文档:
const topicSchema = new mongoose.Schema({ author: { type: String, ref: "User", required: true, }, title: { type: String, required: true }, content: { type: String, required: true, }, // 改成mongoose的ObjectId数组,关联Post模型(注意模型名通常为单数) posts: [{ type: mongoose.Schema.Types.ObjectId, ref: "Post" }], postCount: { type: Number, default: 1, required: true }, createdAt: { type: Date, default: Date.now, }, });
2. 修复路由中的异步查询与关联逻辑
使用async/await处理异步查询,确保拿到实际的Topic文档,同时要保存更新后的Topic:
router.post("/:topicId", async (req, res) => { try { const { topicId } = req.params; // 等待异步查询完成,拿到实际的Topic文档 const topic = await Topic.findById(topicId); // 先判断主题是否存在 if (!topic) { return res.status(404).send("主题不存在"); } const post = new Post({ author: req.body.author, message: req.body.message, // 假设这里的message是你处理后的表单内容 }); // 将新帖子的ID推入主题的posts数组 topic.posts.push(post._id); // 同时更新postCount topic.postCount += 1; // 先保存帖子,再保存主题 await post.save(); await topic.save(); res.redirect("/"); } catch (err) { console.log(err); res.status(500).send("发布回复失败"); } });
额外注意点
- 确保你的Post模型名称是
Post(和Schema里的ref一致),如果模型名是Posts,ref也要对应改成Posts - 使用
try/catch捕获异步操作中的错误,避免程序崩溃 - 必须调用
topic.save(),否则主题的posts数组更新不会同步到数据库
内容的提问来源于stack exchange,提问作者Dagger
相关产品推荐
相关产品推荐

