How to make Mongoose multiple collections using Node.js ?

31 May, 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 creating a collection with Mongoose you have to create 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 the 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 the Model. Therefore, it acts as an interface for the MongoDB database for creating, reading, updating, and deleting a document.
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 create, and then we are exporting all the models created so that they can be imported into the file in which we will create our collections.
main.js: It is the main server file here we have inserted data into a collection.
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});  // Teacher Modal Schemaconst teacherSchema = new mongoose.Schema({    name: String,    teacher_id: Number,    courseId: Number})  // Creating model objectsconst Course = mongoose.model('course', courseSchema);const Student = mongoose.model('student', studentSchema);const Teacher = mongoose.model('teacher', teacherSchema);  // Exporting our model objectsmodule.exports = {    Student, Course, Teacher}
Step 3: Database connection can be easily established using mongoose like:
mongoose.connect('mongodb://localhost:27017/GFG',
{  
   useNewUrlParser: true,  
   useUnifiedTopology: true,  
   useFindAndModify: false
});
If database GFG is already present connection will be established otherwise the first database will be created and a connection will be established Here initially we have an empty database GFG as shown in the image below:
Initially database is empty
Create data objects, you want to insert, for all the collection then insert as shown in main.js file. As soon as we will insert data our collections will automatically be created.
Step 4: Write down the following code in the main.js file.
main.js
const mongoose = require('mongoose');const { Student, Course, Teacher } = require('./model.js');  // Connecting to databasemongoose.connect('mongodb://localhost:27017/GFG',    {        useNewUrlParser: true,        useUnifiedTopology: true,        useFindAndModify: false    });  // Creating array of course data objectconst courseData = [{    _id: 01,    name: "NodeJS",    category: "Backend"},{    _id: 02,    name: "MongoDB",    category: "Database"}]  // Creating array of student data objectsconst studentData = [{    name: "John",    enroll: 1801,    courseId: 01}]  // Creating array of teacher data objectconst teacherData = [{    name: "TeacherX",    teacher_id: 9901,    courseId: 01},{    name: "TeacherY",    teacher_id: 9902,    courseId: 02}]  // Inserting course dataCourse.insertMany(courseData)    .then(value => {        console.log("Saved Successfully");    })    .catch(error => {        console.log(error);    })  // Inserting student dataStudent.insertMany(studentData)    .then(value => {        console.log("Saved Successfully");    })    .catch(error => {        console.log(error);    })  // Inserting teacher dataTeacher.insertMany(teacherData)    .then(value => {        console.log("Saved Successfully");    })    .catch(error => {        console.log(error);    })
Step 5: Run main.js file using the below command:
node main.js
Output: We can see in the console that all the data is saved successfully.
Output after executing main.js
Database: Now we can see that three collections courses, students, teachers are created in our database GFG.
Database after the creation of multiple collections
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.