[MONGOOSE] parent child comment with replies - fourslickz/notes GitHub Wiki

const mongoose = require('mongoose');
const { Schema } = mongoose;

// Comment Schema
const CommentSchema = new Schema({
  content: String,
  author: String,
  postId: { type: Schema.Types.ObjectId, ref: 'Post' }, // Reference to the post
  parentComment: { type: Schema.Types.ObjectId, ref: 'Comment', default: null }, // Reference to the parent comment
  replies: [{ type: Schema.Types.ObjectId, ref: 'Comment' }], // Array of replies (child comments)
  date: { type: Date, default: Date.now }
});

const Comment = mongoose.model('Comment', CommentSchema);

module.exports = Comment;

--- create a comment

const mongoose = require('mongoose');
const Comment = require('./models/comment'); // Assuming the schema is in models/comment.js

async function createRootComment() {
  const comment = new Comment({
    content: 'This is a root comment.',
    author: 'John Doe',
    postId: '64e6f7687e48d3a8e47d9ef2' // Example Post ID
  });

  await comment.save();
  console.log('Root comment created:', comment);
}

createRootComment();

--- create reply to a comment

async function createReply(parentCommentId) {
  const reply = new Comment({
    content: 'This is a reply to the root comment.',
    author: 'Jane Doe',
    postId: '64e6f7687e48d3a8e47d9ef2', // Example Post ID
    parentComment: parentCommentId // Reference to the parent comment
  });

  await reply.save();

  // Add this reply to the parent comment's replies array
  await Comment.findByIdAndUpdate(parentCommentId, { $push: { replies: reply._id } });

  console.log('Reply created:', reply);
}

createReply('64e6f7687e48d3a8e47d9ef3'); // Pass the parent comment ID

--- Embedding Replies Directly in the Parent Comment

const mongoose = require('mongoose');
const { Schema } = mongoose;

// Embedded Reply Schema
const ReplySchema = new Schema({
  content: String,
  author: String,
  date: { type: Date, default: Date.now }
});

// Comment Schema with Embedded Replies
const CommentSchema = new Schema({
  content: String,
  author: String,
  postId: { type: Schema.Types.ObjectId, ref: 'Post' },
  replies: [ReplySchema], // Embedding replies directly
  date: { type: Date, default: Date.now }
});

const Comment = mongoose.model('Comment', CommentSchema);

module.exports = Comment;