Creating table relationships with populate in NoSQL Database

Benjamin Ajewole
2 min readApr 5, 2020

I decided to write this short article on how to use populate() in Mongoose. I was trying to implement relationships in NoSQL environment as I did easily with SQL but I ran into issues because I thought NoSQL would handle it for me. With the help of a friend, I was able to fix it.

Populate() lets you reference documents in other collections.

In this article, we will be working with two collections; company collection and project collection. Company collection has many projects

company.js

We just created the company model that contains the name and also projects. So, the projects column is referencing our Projects model that we are about to create.

project.js

Project.js contains the model for projects. It has the company_id, title and summary.

Add to company collection

const company = await Company.create({name: ‘Vision 2020})

Add to project collection

We added the title, summary and picked company_id from the company we created earlier. Next is to update the company that was created with the project’s id that we just created by pushing into it since it’s an array.

We have gotten to where we are going to use populate() remember it’s used to reference documents in other collections.

To get a company with all the projects associated with

const company = await Company.findById({ _id }).populate(‘projects’);

Result

You can also filter out the populate result

const company = await Company.findById({ _id }).populate({
path: ‘projects’, match: {company_id: "5e89a8bb40c72652b643137d"})

Happy coding!!

Remember to stay safe!!

--

--