Reputation: 2832
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
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:
Each of these is correct and works. Which one is the best really depends on your usage - your app. Examples:
further info here: http://docs.mongodb.org/manual/core/data-model-design/
Upvotes: 2