Mongoose Many-to-Many related models with NodeJS/Express, MongoDB

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

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

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 Mongoose Many-to-Many related documents with NodeJS/Express, MongoDB. Project structure:

Many-to-Many related models

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

-> SubjectSchema:

-> StudentSchema:

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

We use populate() to get the Subject information in Student:

We didn’t add our students to subjects, how to get all students that learnt the same particular subject?

-> One way, we create a references array field of students in SubjectSchema as below:

But What is problem with above way? -> We have two places where the information relating students and subjects needs to be maintained.

What is the better solution?

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

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 Schemas

Subject Schema

Student Schema

Route

Init Data Route

Subject Routes

Student Routes

Controller

Init Data Controller

Subject Controller

Student Controller

Run & Check results

Run MongDB server by commandline:

Run NodeJS/Express application:

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

nodejs-express-mongodb-mongoosejs-many-to-many-related-documents-init-data

– Get All Subjects
-> http://localhost:8081/api/subjects

nodejs-express-mongodb-mongoosejs-many-to-many-related-documents-get-all-subjects

– Get All Students
-> http://localhost:8081/api/students

nodejs-express-mongodb-mongoosejs-many-to-many-related-documents-get-all-students

– Find Student by Name
-> http://localhost:8081/api/students/Peter

– Find Students learnt a given subject Id
-> http://localhost:8081/api/students/subject/5ad006faa6996d2634ff65f5

nodejs-express-mongodb-mongoosejs-many-to-many-related-documents-find-student-learnt-a-given-subject-id

Sourcecode

Nodejs-Mongoose-Many-To-Many

By JavaSampleApproach | April 13, 2018.

Related Posts


Got Something To Say:

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

*