mammy wood
mammy wood

Reputation: 143

post comment replies schema using mongoose

I cant think of a way to create a proper schema to handle post, comments, and also replies. Mainly stuck on how i'll deal with replies to a comment. Basically like reddit where they a post and then replies and you can reply to each persons reply

Comments visually

enter image description here

(assume they are all replying on a post page with a title)

const CommentSchema = new mongoose.Schema({
    username: {
        type: String,
        required: true,
    },

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


})


const PostSchema = new mongoose.Schema({
    author: {
        type: String,
        required: true,
    },
    title: {
        type: String,
        required: true
    },

    description: {
        type: String,
        required: true
    },
    comments: [CommentSchema]





})

The above schema I made does not handle responses to other comments. How can I also handle responses?

Upvotes: 1

Views: 2301

Answers (1)

J Livengood
J Livengood

Reputation: 2738

If you hard combine the comments CommentSchema into the Post Schema, you'll always be pretty limited to the number of layers you hardcode.

Instead, its best practice to reference other documents without combining them. For example (and this is only 1 way of many):

Remove the comments: [CommentSchema] from the PostSchema.

const CommentSchema = new mongoose.Schema({

    // always require all comments to point to the top post, for easy query of all comments whether nested or not
    postId: {
        type: ObjectId,
        ref: 'posts',
        required: true,
    }

    parentCommentId: {
        type: ObjectId,
        ref: 'comments',
        required: false, // if not populated, then its a top level comment
    }
 
    username: {
        type: String,
        required: true,
    },

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

})

Now when you load the Post, do a query to get all comments with postId: post._id and display them graphically as you wish. The other major pattern possible if instead of referencing up from comment to post, you reference down from post to comment [to comment, etc] which allows lookups but not as easy simple querying.

Good luck!

Upvotes: 5

Related Questions