Introduction
When you're designing your schemas, you may want to reference the data of one document in another document. This is where model.populate() comes in.
It is especially useful when you have a one to many relationship between entities.
To see this in action, we'll need two schemas where one schema is kind of a parent to the other. In this post, I'll be using a Post and a Comments schema.
Let's jump in!
In post.model.js:
const mongoose = require('mongoose');
const { Schema } = mongoose;
const postSchema = new Schema({
username: String,
post: String,
comments: [{type: mongoose.Types.ObjectId, ref: Comment}]
});
module.exports = mongoose.model('Post', postSchema);
When you look at comments in the above model, you'll see its of type ObjectId, that's because we'll e pushing ids of the comment to it.
The ref is a reference to the Comment document.
In comment.model.js:
const mongoose = require('mongoose');
const { Schema } = mongoose;
const commentSchema = new Schema({
comment: String,
By: String
});
module.exports = mongoose.model('Comment', commentSchema);
Having done that, lets now see how we add the comment to a post.
Having the comment below:
const comment = {
_id: 5d53612dc952f76e446d7d9b,
comment: 'Well, it may have escaped your notice, but life isn’t fair.'
By: 'Severus Snape'
}
To add it to a post:
let addCommentToPost = async (id, comment) => {
let post = await Post.findById(id);
post.comments.push(comment);
await post.save();
return post;
}
The returned post collection:
{
_id : 5d73622dc452f69e446d2d9b,
username: "Hermione Granger",
post: 'I’m hoping to do some good in the world!',
comments : ['5d715243c252f08e235d1d9c']
}
To retrieve a post with all the comments:
function getPost(id) {
return post
.findById(id)
.populate("comments")
.exec()
}
The returned post:
{
_id : 5d73622dc452f69e446d2d9b,
username: 'Hermione Granger',
post: 'Im hoping to do some good in the world!',
comments : [{
_id: 5d53612dc952f76e446d7d9b,
comment: 'It may have escaped your notice, but life isn’t fair.'
By: 'Severus Snape'
}]
}
Conclusion
The model.populate() method is an essential method to use when referencing one document in another. Just use type ObjectId and a ref to the document you want to get data from and you're set!
Top comments (0)