how to correctly structure mongoose (mongoDb) model with relationships?

Viewed 20

I am new to backend development, I want to build a comment system which supports replies. I am stuck on how to structure my mongoose model

I am looking at having three models one for users, one for the post, and one for comments

for user

import mongoose from "mongoose";

const UserSchema = new mongoose.Schema({
  name: { type: String, required: [true, "Name is required"] },

  email: { type: String, required: [true, "email is required"] },

  password: {
    type: String,
    required: [true, `password is required`],
  },
  isAdmin: {
    type: Boolean,
    default: false,
    required: true,
  },
  image: { type: String, required: [true, `please provide a photo`] },
});

export default mongoose.models.User || mongoose.model("User", UserSchema);

for post

import mongoose from "mongoose";

const PostSchema = new mongoose.Schema(
  {
    title: {
      type: String,
      required: [true, "Please provide a name for this Article"],
    },

    description: {
      type: String,
      required: [true, `please provide a description for this article],
    },

    image: {
      type: String,
      required: true,
    },

    keywords: {
      type: Array,
      required: true,
    },

    body: {
      type: String,
      required: [true, `please provide a body for this article],
    },

    author: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
  },
  { timestamps: true }
);


export default mongoose.models.Post || mongoose.model("Post", PostSchema);

for comment

import mongoose from "mongoose";

const CommentSchema = new mongoose.Schema({
   user: { type: mongoose.Schema.Types.ObjectId, ref: "Author" },
   comment: {   type: String,
      required: [true, `please provide a message for this comment`],}
   replies: {type: Array}
});

export default mongoose.models.Comment || mongoose.model("Comment", CommentSchema);

I am stuck, every reply for comment is itself a comment, how do I relate the reply to the comment?

also, how do I relate the comment and the post?

0 Answers
Related