mvbl fst
mvbl fst

Reputation: 5263

How to store threaded comments using MongoDB and Mongoose for Node.js?

What would be the best way to store comments trees in MongoDB and Mongoose? Currently I have this:

CommentableSchema = new Schema({
    ...
});

ReplySchema = new Schema({
    userId: Number,
    'body': String,
    createdAt: Date,
    updatedAt: Date
});

CommentSchema = new Schema({
    commentable: CommentableSchema,
    userId: Number, // users are NOT stored in MongoDB
    subject: String,
    'body': String,
    createdAt: Date,
    updatedAt: Date,
    replies: [ReplySchema],
    length: Number // comment + all replies
});

But this seems to be suitable only for top level comment + 1 more level of comments. I am fairly certain that I can not use ReplySchema inside ReplySchema.

Upvotes: 5

Views: 10963

Answers (1)

kroe
kroe

Reputation: 1126

You can also use the populate function from mongoose: http://mongoosejs.com/docs/populate.html

From the official manual, here's more information: https://docs.mongodb.com/manual/applications/data-models-tree-structures/

Upvotes: 7

Related Questions