1

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:

enter image description here

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:

enter image description here

So you can clearly see that there is no subforum in the array.

What is the problem and how can I fix it?

1 Answer 1

1

I don't see anywhere in your code where you are actually pushing the subforum id to the forum.subforum array. After you create your subforum and save it, you must also push that subforum id into the forum.subforums array and save that as well.

Sign up to request clarification or add additional context in comments.

2 Comments

Thx that makes sense: So something like that: pastebin.com/KjDBB9s9
Thanks man. I somehow thought adding the forum id to the subforum is enough.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.