我正在一个论坛上工作。这是我的主题架构
const topicSchema = new mongoose.Schema({
author: {
type: String,
ref: "User", // Reference to the user who made the Topic update
required: true,
},
title: { type: String, required: true },
content: {
type: String,
required: true,
},
posts: { type: Array, ref: "Posts" }, // posts array
postCount: { type: Number, default: 1, required: true },
createdAt: {
type: Date,
default: Date.now,
},
});
使用此架构和用户填写的表单,此代码将输入的数据保存到数据库中。
const topic = new Topic({
title: req.body.title,
content: content,
author: req.body.author,
});
我的消息响应有类似的代码。我有一个帖子架构,用于保存帖子消息和作者。
router.post("/:topicId"
const { topicId } = req.params;
const topic = Topic.findById(topicId);
const post = new Post({
author: req.body.author,
message: message,
});
console.log(post);
console.log(topic.title);
topic.posts.push(post);
// Data from form is valid. Save statue update.
post
.save()
.then(function (post) {
res.redirect("/");
})
.catch(function (err) {
console.log(err);
});
我的代码的一切都运行得很好。当我在任一表单中创建主题或做出帖子回复时,它都会按预期工作,并且我得到零错误。
我的问题在于在我的邮政编码中使用
push
,这是我收到的错误:Cannot read properties of undefined (reading 'push')
。我希望这样,当用户在某个主题内创建帖子时,消息内容会被推送到该主题的 posts
字段(主题架构),这样我就可以循环遍历所有帖子以显示响应这一页。但每次我尝试将帖子添加到主题时,我都会收到上述未定义的错误。
猫鼬查询可以通过两种方式之一执行。
在调用
Topic.findById
时,您不会将其视为异步调用。然后,当您调用 topic.posts.push(post)
时,由于 posts 未定义,您会收到 "Cannot read properties of undefined"
错误。在将新项目推送到 posts 数组之前,您需要等待 Model.findById 调用的结果。例如,
const { topicId } = req.params;
// Use async/await to fetch the topic from the database
const topic = await Topic.findById(topicId);