User, post, and comment model in mongoose

Viewed 453

I am making a forum app that is quite similar to Reddit. I am using mongoose here for schema design. I have some doubts regarding models that I have- User, Post and Comment.

  • Does the schema look all right of all the models?
  • In User, I want to show the friends on the user profile. Like when you go to his profile, there will be like Friends(200), and when I click the friend list will appear(like Facebook, then on clicking you can access friends' profiles). I haven't created Friend schema, but does it needed actually?
  • Question about comments. So far, I have the basic comment schema. What happens to the threaded comments or replies. How do I store them?

All the models that I have currently:

const userSchema = new Schema(
  {
    username: { type: String, required: true },
    email: { type: String, reuired: true },
    password: { type: String, required: true },
    country: { type: String, required: true },
    friends: [{ type: Schema.Types.ObjectId, ref: "Friend" }], // is it needed?
    posts: [{ type: Schema.Types.ObjectId, ref: "Post" }],
  },
  { timestamps: true }
)
const postSchema = new Schema(
  {
    title: { type: String, required: true },
    description: { type: String, required: true },
    user: { type: Schema.Types.ObjectId, ref: "User" },
    slug: { type: String, slug: "title" },
    upvotes: { type: Number },
    downvotes: { type: Number },
    city: { type: String }, // post will have a tag by the city like NewYork, LA etc.
  },
  { timestamps: true }
)
const commentSchema = new Schema(
  {
    comment: { type: String, required: true },
    post: { type: Schema.Types.ObjectId, ref: "Post"},
    user: { type: Schema.Types.ObjectId, ref: "User"},
    upvotes: { type: Number },
    downvotes: { type: Number }
  },
  { timestamps: true }
)
2 Answers

For the Second Question you don't need friend schema since friend is also a user.

For the first question, Why do intend to store all the posts of a user inside the User object as a list of posts, this would mean fetching 100s of posts even when something basic like username or email is required. Instead, you can place user_id in the Post Schema, helping to identify posts from a particular User.

Related