I'm in the process of developing a forum platform. Below is my Topic schema:
const topicSchema = new mongoose.Schema({
author: {
type: String,
ref: "User", // Reference to the user who created the Topic
required: true,
},
title: { type: String, required: true },
content: {
type: String,
required: true,
},
posts: { type: Array, ref: "Posts" }, // array of posts
postCount: { type: Number, default: 1, required: true },
createdAt: {
type: Date,
default: Date.now,
},
});
This code snippet utilizes the above schema and a form filled out by the user to store data into the database.
const topic = new Topic({
title: req.body.title,
content: content,
author: req.body.author,
});
A similar approach is taken for managing message responses with a Posts schema which saves messages and their authors.
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);
// Save new post if form data is valid.
post
.save()
.then(function (post) {
res.redirect("/");
})
.catch(function (err) {
console.log(err);
});
Overall, my code is functioning well without errors. However, I am facing an issue with using push
in the post section resulting in the following error:
Cannot read properties of undefined (reading 'push')
. The goal is to append a user's post under a specific topic so that all responses can be displayed on the page. Despite several attempts, this action triggers the mentioned undefined error.