NodeJs/Express MongoDB One-to-Many related documents


In the tutorial, we will show you how to develop One-to-Many related document with NodeJs/Express, MongoDB using Mongoose.

Related post:
Crud RestAPIs with NodeJS/Express, MongoDB using Mongoose
Mongoose Many-to-Many related models with NodeJS/Express, MongoDB



Crud RestAPIs with NodeJS/Express, MongoDB using Mongoose
In the above tutorial, we show how to build CRUD RestAPIs with NodeJS/Express and MongoDB using Mongoose:


In the tutorial, we show how to develop One-to-Many related documents with NodeJS/Express, MongoDB. Project structure:

One-to-Many related models

For working with related documents, we use the ObjectId schema field.

-> CompanySchema:

-> ProductSchema:

We can save the references to the related document by assigning the _id value:

We use populate() to get the Company information in Product:

We didn’t add our products to companies, how to get all products by a particular company?

One way, we create a references array field of products in CompanySchema as below:

BUT What is problem? -> We have two places where the information relating companies and products needs to be maintained.

What is the better solution?

-> We get the _id of our company, then use find() to search for this in the company field across all products.


Create a NodeJS/Express project

Following below guide:
Crud RestAPIs with NodeJS/Express, MongoDB using Mongoose

See dependencies in ‘package.json’ file:

Create Model Schema




Company Routes:

Product Routes:


Company Controllers:

Product Controllers:

Run & Check results

Run MongDB server by commandline:

Run NodeJS/Express application:

– Initial data
-> localhost:8081/api/companies/init

nodejs-mongodb-one-to-many-related-document-initial data

– Get all Companies
-> localhost:8081/api/companies

nodejs-mongodb-one-to-many-related-document-find all company

– Get all Products
-> localhost:8081/api/products

nodejs-mongodb-one-to-many-related-document-find all product

– Find Product by Name
-> localhost:8081/api/product/Iphone7

nodejs-mongodb-one-to-many-related-document-find product by name - polulate company

– Find Products by Company Id
-> localhost:8081/api/products/company/5acd590b203d8e1ac01cb184

nodejs-mongodb-one-to-many-related-document-find all products by company id



By grokonez | April 11, 2018.

Last updated on September 28, 2018.

Related Posts

2 thoughts on “NodeJs/Express MongoDB One-to-Many related documents”

  1. This is really great and a lot helpful guide while I was starting a project. The code structure really guided me in a certain way.
    You could also give us the best way to design a server side folder structure (a better approach).

Got Something To Say:

Your email address will not be published. Required fields are marked *