How Do I Reference A Schema in Mongoose?
I am a Software Engineer, Tech Writer based in Lagos, Nigeria. I am passionate about solving problems, sharing knowledge gained during my Tech journey, and excited in meeting people.
Introduction
Hi there, welcome to my blog once again. I feel excited while writing this article after a long time of taking a break.
Please join me as we learn together how to reference a schema using Mongoose.
What is a Schema?
A Schema is a blueprint for defining data structure in Mongoose. It tells you what the data will look like and the accepted format.
Example:
const userSchema = new Schema({
full_name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
}
password: {
type: String,
required: true,
}
});
mongoose.model('user', userSchema);
With the example above, you will notice that a User is required to have a name in full, email, and password. This is a type of blueprint.
How do we reference another schema?
Let's use a user's post on Facebook as an example. Users on Facebook write and comment on posts all the time, now how do we connect a user with posts? We reference it.
We are going to create a postSchema. We are going to use the ref property and Mongoose.schema.ObjectId to reference the userSchema.
const postSchema = new Schema({
post: String,
postMadeBy: {
type: Mongoose.schema.ObjectId,
ref: 'user',
},
});
mongoose.model('post', postSchema);
This is our postSchema.
Explanation:
You will observe that it contains post and postMadeBy properties. postMadeBy has it's own properties of type and ref which points to Mongoose.schema.ObjectId and user respectively.
When a user makes a post, the id of that user is attached alongside the post made and referenced in the database. So it will be something like this:-
{
"_id" : ObjectId("6086b0f46aae7f44f2fc1b42"),
"post" : "Hello World!!",
"postMadeBy" : ObjectId("608d7be038513c2c08c5db12"),
"__v" : 0
}
You can achieve it too
I hope you enjoyed the read. Please feel free to connect with me on Twitter https://twitter.com/etienejames5 and LinkedIn: https://www.linkedin.com/in/etiene-essenoh/
Don't forget to react to this post.
Thanks. See you again soon.




