bob_cobb
bob_cobb

Reputation: 2269

Nested (children) comments within a single parent comment in MongoDB

Question: Do I nest my child comments within a single parent comment or not?

Overview:

Schema looks like:

SubmissionCommentsSchema = new Schema({
  id : Schema.ObjectId,
  submission_id : {
    type: String
  },
  parent_id : {
    type: String,
    default: null
  },
  comment : {
    type: String,
    required: true
  },
  user_id: {
    type: String,
    required: true
  },
  username : {
    type: String,
    required: true
  },
  created : {
    type: Date,
    default: Date.now
  },
  reply : {
    type: Boolean,
    default: false,
    required: true
  },
  deleted : {
    type: Boolean,
    default: false
  }
});

Example of a parent comment:

  { submission_id: '51899313634afe0000000051',
    comment: 'asdfadsf',
    user_id: '516e173f48670b44d20004dc',
    username: 'bobcobb',
    _id: 51899338634afe0000000055,
    deleted: false,
    reply: false,
    created: Tue May 07 2013 16:50:16 GMT-0700 (PDT),
    parent_id: null },

Example of a child comment referencing the above parent comment:

  { submission_id: '51899313634afe0000000051',
    comment: 'Testing one two four',
    user_id: '516b45f8ac6a1b488e000001',
    username: 'testing',
    _id: 519d93a83867470000000146,
    deleted: false,
    reply: false,
    created: Wed May 22 2013 20:57:28 GMT-0700 (PDT),
    parent_id: '51899338634afe0000000055' },

Should I just store the children comments within the original parent comment as a nested array?

Upvotes: 1

Views: 1749

Answers (1)

Ian Mercer
Ian Mercer

Reputation: 39277

Probably not since you may well overflow the document size limit if a particular thread receives many replies.

What you might want to do however is add an integer depth field to the comments so you can easily fetch, say, the top 2 levels, display them, and then load subsequent levels only as the user expands the comment tree.

Sometimes it's also worth maintaining an array of ancestor ids so you can quickly fetch any sub-tree, or given a deep-link to a specific comment can quickly figure out what comments you need to load 'above' it to display the minimally-expanded comment tree that includes it.

Upvotes: 3

Related Questions