Reputation: 89
So, I have a (mongoose) Post model and Comment model, and i would like to link the two without storing entire subdocuments, my requirements are for there to be an array of references to children Comments in a Post and for a Comment to have a single reference to its parent Post. Edit: Would it be possible to have the references set automatically?
Upvotes: 0
Views: 617
Reputation: 744
You have to use mongoose.Schema.Types.ObjectId
type in order to reference to another collection. It works like foreignKey in SQL language.
But the answer of your second question is No. You have to set it up manually.
By the way, the better design is to store your reference or foreignKey in one of the two collections, not both of them.
In database language if you have one-to-many
relationship, like here where your post has many comments, the better way is to store postId (as a foreignKey) in comment collection. And when you want you find all the comments of a specific post you can query your comments collection and find only records which have your specific postId.
Here is the comment schema:
let commentSchema = new mongoose.Schema({
text: String,
post: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Post'
}
});
Here is the post schema
let postSchema = new mongoose.Schema({
text: String,
comments: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Comment',
default: []
}]
});
And here is the code for creating a post and comments:
const createPost = async () => {
let post = new PostModel({
text: 'Here is a sample post',
});
await post.save();
}
const createCommentOnPost = async (postId) => {
let comment = new Comment({
text: 'Sample comment',
post: postId
});
await comment.save();
await Post.updateOne({_id: postId}, {$push: {comments: comment}});
}
Upvotes: 1