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

22 Jun, 2021
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:
Schema: It is a document structure that contains the property with its types (default value, validations, etc. when required) as a key-value pair.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.
Schema: It is a document structure that contains the property with its types (default value, validations, etc. when required) as a key-value pair.
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 moduleconst mongoose = require('mongoose');    // Course Modal Schemaconst courseSchema = new mongoose.Schema({    _id: Number,    name: String,    category: String});    // Student Modal Schemaconst studentSchema = new mongoose.Schema({    name: String,    enroll: Number,    courseId: Number});     // Creating model objectsconst Course = mongoose.model('course', courseSchema);const Student = mongoose.model('student', studentSchema);    // Exporting our model objectsmodule.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 moduleconst mongoose = require('mongoose');  // Importing Models Student and Course from model.jsconst { Student, Course } = require('./model');  // Connecting to databasemongoose.connect('mongodb://localhost:27017/GFG',    {        useNewUrlParser: true,        useUnifiedTopology: true,        useFindAndModify: false    });  var dbcourse = [];  // Finding courses of category DatabaseCourse.find({ category: "Database" })    .then(data => {        console.log("Database Courses:")        console.log(data);          // Putting all course id's in dbcourse arrray        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
Mongoose
Node.js-Methods
NodeJS-Questions
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to build a basic CRUD app with Node.js and ReactJS ?
How to connect Node.js with React.js ?
Mongoose Populate() Method
Express.js req.params Property
How to Convert CSV to JSON file having Comma Separated values in Node.js ?
Top 10 Front End Developer Skills That You Need in 2022
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript