lets say I have one to many relation with Post and Comment models.
When embedding is not used he suggested way to handle data relation is:
const PostSchema = new Schema({
_id: Types.ObjectId,
comments: [{type: Types.ObjectId, ref:'comment'}]
})
const CommentSchema = new Schema({
_id:Types.ObjectId
})
Wouldnt the schema design below be more appropriate?(storing postId as foreign key in Comment). And also is there a name for such relation method?
const PostSchema = new Schema({
_id: Types.ObjectId
})
const CommentSchema = new Schema({
_id:Types.ObjectId,
postId: Types.ObjectId
})
To get a post and all its comments I would simply do:
let post = await Post.find({ _id: postId });
post.comments = await Comment.find({ postId });
With the first method, every time a new comment is created, the post document must be updated as well. And if we want to guarantee that commentId is added to comments array, we should use transaction, which makes this update even more costly.
However with the second approach, we only have to create comment.
Now the downside is that I will not be able to use $lookup, but performance wise, would it make much of a difference? $lookup is not like JOIN in relational databases, where JOINs are done in a single database operation. So using $lookup or simply querying by comment's postId(indexed) to "JOIN" the data would not make much of a difference in terms of performance.