Shambu
Shambu

Reputation: 2832

Is it necessary hold references to children in parent document -Mongooose

In below example, I want to retrieve post document filled with corresponding comments.

Do I need to hold references to comments in post as an array? Holding array with reference to comments would mean that the post document would be updated quite regularly whenever a new document is updated.

 var Post = new schema({
       content:String,
       author:{ type: Schema.ObjectId, ref: 'User' },
       createdOn:Date
    });

var Comment = new Schema({
   post : { type: Schema.ObjectId, ref: 'Post' },
   commentText : String,
   author: { type: Schema.ObjectId, ref: 'User' },
   createdOn:Date
});
mongoose.model('Post',Post);
mongoose.model('Comment',Comment);

If I hold references of Comment._Id in Post as an array, then in mongoose I can populate as below.

Post.findById(postid).populate('Comments').exec( callback);

But I do not want to update post document whenever a new a comment is created as you need to push the comment id into post document. Comment has reference to Post which it belongs, so technically speaking, it is possible to retrieve comments belonging to a particular post, but if you want to retrieve or send single json document is it possible without having array containing references to comments in post document?

Upvotes: 2

Views: 1033

Answers (1)

Reto
Reto

Reputation: 3141

As always with data modelling there are just multiple ways to do things with advantages/disadvantages. Often more than one way is good enough for your app.

The question you are asking is a typical 1:n relationship, so you may:

  1. store backrefs from the children to the parent
  2. store an array of refs on the parent to the children
  3. store two-way referencing by doing 1. and 2.
  4. store the comments directly inside the post object as an array of sub-documents (comment-objects) inside the post-document.

Each of these is correct and works. Which one is the best really depends on your usage - your app. Examples:

  • If you have lots of concurrent creates of comments for one post, then 1. is probably a good choice, because you don't need to concurrently update the post object. But you will always need two queries to display a Post with its comments.
  • If you are never displaying a comment without its post, and if one comment always belongs to exactly one post, 4. may be a good choice - probably the typical choice with mongodb (a no-sql choice). -> Only one query to display a post with comments.
  • If you have single posts with lots of comments and it is important for your performance to be able to load only a subset of comments, 4. is a bad choice.
    1. is probably best if you need all flexibilty, whenever you cannot predict the usage and performance is not an issue.

further info here: http://docs.mongodb.org/manual/core/data-model-design/

Upvotes: 2

Related Questions