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

Goal

Prerequisites

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:

Objective

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.

Practice

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

CompanySchema:

ProductSchema:

Route

Company Routes:

Product Routes:

Controller

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

Sourcecode

NodeJS-MongoDB-One-to-Many

By JavaSampleApproach | April 11, 2018.

Related Posts


Got Something To Say:

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

*