The problem
I know there are many similiar problems on Stack about this problem, but I wasn't able to solve it with these posts.
I'm creating a simple Forum application. I have 2 routes for creating a Forum and a Subforum. A Forum can have many Subforum's. A Subforum is assigned to one Forum.
My Schema for Forum looks like this:
const mongoose = require("mongoose");
const forumSchema = new mongoose.Schema({
title: String,
subTitle: String,
posts: [{ type: mongoose.Schema.Types.ObjectId, ref: "Post" }],
subForums: [{ type: mongoose.Schema.Types.ObjectId, ref: "Subforum" }]
});
const Forum = mongoose.model("Forum", forumSchema);
module.exports = Forum;
The Schema for the Subforum:
const mongoose = require("mongoose");
const subForumSchema = new mongoose.Schema({
title: String,
subTitle: String,
posts: [{ type: mongoose.Schema.Types.ObjectId, ref: "Post" }],
forum: { type: mongoose.Schema.Types.ObjectId, ref: "Forum" }
});
const SubForum = mongoose.model("Subforum", subForumSchema);
module.exports = SubForum;
If I create a new forum and save it I have it in the database. Of course with no Subforums yet.
Then I create a Subforum like this (I provide the id of the just created forum with req.body.forum):
router.post("/newSub", verify, async (req, res) => {
// TODO: Only admin can do this
const subForum = new SubForum({
title: req.body.title,
subTitle: req.body.subTitle,
forum: req.body.forum
});
try {
await subForum.save();
res.send(subForum);
} catch (err) {
res.status(400).send(err);
}
});
I get the response back that it has been created. The new Subforum looks like this:
But when I search for all forums and want to populate it with it's sub forums it won't work. In Robomongo it looks like this:
So you can clearly see that there is no subforum in the array.
What is the problem and how can I fix it?

