Open In App

How to get data from 2 different collections of mongoDB using Node.js ?

Last Updated : 28 Jul, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Mongoose is an Object Data Modeling (ODM) library for MongoDB. It defines a strongly-typed-schema, with default values and schema validations which are later mapped to a MongoDB document.

For getting data from a collection with Mongoose in NodeJS you have to have two necessary things:

  1. Schema: It is a document structure that contains the property with its types (default value, validations, etc. when required) as a key-value pair.
  2. Model: It is a class created with the help of defined Schema and a MongoDB document is an instance of Model. Therefore, it acts as an interface for the MongoDB database for creating, reading, updating, and deleting a document.

After having a model, we can use method find() on the model of a particular collection to get documents of the collection.

Syntax: 

<Model_Name>.find(<query>,<projection>)
  • <query>: It is optional. It specifies a selection filter that is used to filter documents using various MongoDB query operators. If not passed, all the documents are returned.
  • <projection>: It is optional. It contains fields that we want to be returned to the documents that match the query filter. If not passed, all the fields are returned.

 

Install Mongoose:

Step 1: You can visit the link Install mongoose to install the mongoose module. You can install this package by using this command.

npm install mongoose

Step 2: Now you can import the mongoose module in your file using:

const mongoose = require('mongoose');

Implementation:

Step 1: Create a folder and add model.js and main.js files into it.

  • model.js: It contains schemas and models for all the collections you want to use, and then we are exporting all the models created so that they can be imported into the file in which we will get data from different collections.
  • main.js: It is the main server file here we will get data from two different collections.

Step 2: Write down the following code in the model.js file.

model.js




// Requiring module
const mongoose = require('mongoose');
    
// Course Modal Schema
const courseSchema = new mongoose.Schema({
    _id: Number,
    name: String,
    category: String
});
    
// Student Modal Schema
const studentSchema = new mongoose.Schema({
    name: String,
    enroll: Number,
    courseId: Number
});
     
// Creating model objects
const Course = mongoose.model('course', courseSchema);
const Student = mongoose.model('student', studentSchema);
    
// Exporting our model objects
module.exports = {
    Student, Course
}


Database: We already have documents in our Courses and Students collections from which we are going to get data as shown below:

Collections Courses and Students in Database GFG

Step 3: Database connection can be easily established using mongoose like:

mongoose.connect('mongodb://localhost:27017/GFG',
{  
  useNewUrlParser: true,  
  useUnifiedTopology: true,  
  useFindAndModify: false
});

Step 4: Write down the following code in the main.js file.

main.js




// Requiring mongoose module
const mongoose = require('mongoose');
  
// Importing Models Student and Course from model.js
const { Student, Course } = require('./model');
  
// Connecting to database
mongoose.connect('mongodb://localhost:27017/GFG',
    {
        useNewUrlParser: true,
        useUnifiedTopology: true,
        useFindAndModify: false
    });
  
var dbcourse = [];
  
// Finding courses of category Database
Course.find({ category: "Database" })
    .then(data => {
        console.log("Database Courses:")
        console.log(data);
  
        // Putting all course id's in dbcourse array
        data.map((d, k) => {
            dbcourse.push(d._id);
        })
  
        // Getting students who are enrolled in any
        // database course by filtering students
        // whose courseId matches with any id in
        // dbcourse array
        Student.find({ courseId: { $in: dbcourse } })
            .then(data => {
                console.log("Students in Database Courses:")
                console.log(data);
            })
            .catch(error => {
                console.log(error);
            })
    })
    .catch(error => {
        console.log(error);
    })


Step 5: Run main.js file using the below command:

node main.js

Explanation: In the above code, in the file main.js, we are getting all the documents of Course collection whose category is Database then storing _id of each course in dbcourse array then getting all the documents from the Student collection whose is enrolled in any course of category Database.

Output: We are getting data from two different collections Courses and Students in the console shown below:

Output after executing main.js



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads