Open In App

How to make Mongoose multiple collections using Node.js ?

Last Updated : 31 May, 2021
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 creating a collection with Mongoose you have to create 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 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 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
});
  
// Teacher Modal Schema
const teacherSchema = new mongoose.Schema({
    name: String,
    teacher_id: Number,
    courseId: Number
})
  
// Creating model objects
const Course = mongoose.model('course', courseSchema);
const Student = mongoose.model('student', studentSchema);
const Teacher = mongoose.model('teacher', teacherSchema);
  
// Exporting our model objects
module.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 database
mongoose.connect('mongodb://localhost:27017/GFG',
    {
        useNewUrlParser: true,
        useUnifiedTopology: true,
        useFindAndModify: false
    });
  
// Creating array of course data object
const courseData = [{
    _id: 01,
    name: "NodeJS",
    category: "Backend"
},
{
    _id: 02,
    name: "MongoDB",
    category: "Database"
}]
  
// Creating array of student data objects
const studentData = [{
    name: "John",
    enroll: 1801,
    courseId: 01
}]
  
// Creating array of teacher data object
const teacherData = [{
    name: "TeacherX",
    teacher_id: 9901,
    courseId: 01
},
{
    name: "TeacherY",
    teacher_id: 9902,
    courseId: 02
}]
  
// Inserting course data
Course.insertMany(courseData)
    .then(value => {
        console.log("Saved Successfully");
    })
    .catch(error => {
        console.log(error);
    })
  
// Inserting student data
Student.insertMany(studentData)
    .then(value => {
        console.log("Saved Successfully");
    })
    .catch(error => {
        console.log(error);
    })
  
// Inserting teacher data
Teacher.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



Previous Article
Next Article

Similar Reads

Mongoose Schema Connection.prototype.collections API
The Mongoose Schema API Connection.prototype.collections property of the Mongoose API is used on the Connection object. It allows us to get the details about the collections that are associated with the connection object. Each connection object poses how many collections that information we will get in the hashed format. Let us understand the colle
2 min read
Mongoose mongoose.model() Function
The mongoose.model() function of the mongoose module is used to create a collection of a particular database of MongoDB. The name of the collection created by the model function is always in plural format mean GFG to gfss and the created collection imposed a definite structure. Syntax: mongoose.model(<Collectionname>, <CollectionSchema>
2 min read
How to get data from 2 different collections of mongoDB using Node.js ?
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 wi
4 min read
How to get information of all collections present in MongoDB database using Node.js ?
MongoDB, the most popular NoSQL database, we can count the number of documents in MongoDB Collection using the MongoDB collection.countDocuments() function. The mongodb module is used for connecting the MongoDB database as well as used for manipulating the collections and databases in MongoDB. Installing module: You can install mongodb module using
1 min read
How to Join Two Collections in Mongodb using Node.js ?
Joining two collections in MongoDB using Node.js can be accomplished using the aggregation framework. The $lookup stage in the aggregation pipeline allows you to perform a left outer join to another collection in the same database. Understanding MongoDB CollectionsIn MongoDB, a collection is a group of documents that are stored together within the
4 min read
Node.js authentication using Passportjs and passport-local-mongoose
Passport is the authentication middleware for Node. It is designed to serve a singular purpose which is to authenticate requests. It is not practical to store user password as the original string in the database but it is a good practice to hash the password and then store them into the database. But with passport-local-mongoose you don't have to h
5 min read
How to populate virtuals to a mongoose model using Node.js ?
In Mongoose, the virtual is the property that is not stored in the database, they only exist logically, and you cannot query directly on the basis of this property. To know more about virtual refers to this article Mongoose Virtuals. Populating Virtuals: In MongoDB, Population is the process of replacing the specified path in the document of one co
4 min read
Node.js CRUD Operations Using Mongoose and MongoDB Atlas
Before we look into the major operations and functionality of Mongoose, let us get a brief idea about what it is and how it makes our Node.js project more flexible and user-friendly. MongooseJs: Mongoose is basically a package that serves as a mediator between the NodeJS application and the MongoDB server. It is an Object Document Mapper(ODM) that
7 min read
Understanding Mongoose Middleware in Node.js
A Mongoose is a powerful tool for NodeJS developers working with MongoDB databases. It simplifies database interaction, allowing developers to focus more on building their applications. In this article, we'll cover the basics of Mongoose, including how to connect to a MongoDB database and perform CRUD operations. We'll also explore Mongoose middlew
5 min read
How to Use MongoDB and Mongoose with Node.js ?
In the world of Node.js development, MongoDB is a popular choice for database management due to its flexibility and scalability. When working with MongoDB in a Node.js environment, using Mongoose—a JavaScript library—makes the interaction with the database even more efficient and structured. In this article, we'll explore how to integrate MongoDB a
5 min read