Welcome to this lesson on integrating MongoDB into your NestJS application! In this lesson, we'll build upon our existing To-Do application an add some valuable enterprise-level features. We will be continuing from where we left off last course. Today, we will set the foundation by understanding databases and how MongoDB fits into our application architecture.
Databases are essential components of web applications because they store and manage the data that applications operate on. There are different types of databases, including relational databases like MySQL and PostgreSQL, and NoSQL databases like MongoDB. MongoDB is a NoSQL database that stands out for its flexibility and scalability, making it an excellent choice for modern web applications.
To get started, you need to set up MongoDB. While our CodeSignal environment comes pre-installed with MongoDB, it's important to know how to set it up on your own machine for a deeper understanding.
-
Install Homebrew (if not already installed):
- Follow the instructions on the Homebrew website to install Homebrew.
-
Install MongoDB with Homebrew:
- Open your terminal and run the following command:
-
Run MongoDB:
- Start the MongoDB server by running the following command:
- This starts the MongoDB server locally, typically accessible on
mongodb://localhost:27017
.
But remember, if you are using the CodeSignal environment for this course, MongoDB is pre-installed, and you can directly start coding without worrying about these setup steps.
Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js. It helps in managing relationships between data, provides schema validation, and is used to translate between objects in code and their representation in MongoDB.
To install Mongoose
, use the following command in your terminal within your project directory:
Next, we'll configure Mongoose
in our NestJS application. Open src/app.module.ts
and set up the connection to MongoDB and import the ToDo
module:
Here’s what’s happening:
MongooseModule.forRoot
establishes a connection to a MongoDB instance running locally (mongodb://localhost/nestjs-todo
).- The
TodoModule
will manage our ToDo-related functionality, which we'll define next.
Schemas define the structure of documents in MongoDB. Using Mongoose
, we can create a schema for our ToDo items.
Create a file src/todo/schemas/todo.schema.ts
and define the schema as follows:
Explanation:
@Schema()
: Decorator to mark this class as a Mongoose schema.@Prop()
: Decorator to define schema properties.HydratedDocument<T>
: Mongoose type that represents a document from MongoDB, allows us to use methods likefindById
,findByIdAndUpdate
,delete
, and other Mongoose document methods.SchemaFactory.createForClass(Todo)
is a method provided by NestJS to automatically convert theTodo
class into a Mongoose schema.
The service layer contains the business logic of the application. It will handle creating, reading, updating, and deleting ToDo items. In our previous course, we used an in-memory array for the data. That goes away as soon as you restart your NestJS application. By using a database, we can persist these items beyond the scope of the server process.
Create a file src/todo/todo.service.ts
and implement the service as follows:
Explanation:
TodoService
: Contains methods for CRUD operations.findAll()
: Retrieves ToDo items, with an option to filter incomplete ones.findOne(id)
: Finds a ToDo item by its ID.createTodo()
: Creates a new ToDo item.updateTodo()
: Updates an existing ToDo item by its ID.markTodoComplete()
: Marks a ToDo item as completed.deleteTodo()
: Deletes a ToDo item by its ID.
The controller layer handles incoming HTTP requests and sends responses back to the client. We don't need to change much here except that the TodoService
is now asynchronous. This means that it can take some time for the Mongo requests to complete. We need to update the controller to handle asynchronous TodoService
calls!
Create a file src/todo/todo.controller.ts
and set up the controller:
Explanation:
TodoController
: Maps HTTP requests to service methods.findAll()
: Handles GET requests to fetch all ToDos, with a filter option.findOne(id)
: Handles GET requests to retrieve a ToDo item by ID.create()
: Handles POST requests to create a new ToDo item.update(id)
: Handles PUT requests to update a ToDo item by ID.complete(id)
: Handles PUT requests to mark a ToDo item as completed.remove(id)
: Handles DELETE requests to delete a ToDo item by ID.- Properly handles
NotFoundException
for non-existent ToDo items.
In this lesson, we introduced databases and MongoDB, set up MongoDB in the development environment, installed and configured Mongoose in a NestJS application, defined a schema for ToDo items, built the service layer for CRUD operations, implemented the controller to handle HTTP requests, and tested our integration using HTTP requests.
- Databases: Essential for storing and managing data.
- MongoDB: A flexible and scalable NoSQL database.
- Mongoose: Simplifies MongoDB interactions by providing schema validation and object mapping.
- ToDo Schema: Defines the structure and properties of ToDo items.
- Service Layer: Contains business logic for CRUD operations.
- Controller Layer: Handles HTTP requests and maps them to service methods.
- Testing: Validates the integrations and ensures the application's functionality.
Now that you have a working understanding of integrating MongoDB into a NestJS application, it's time to solidify your knowledge by working on practice exercises. These exercises will help reinforce everything you've learned and give you hands-on experience with the concepts. Happy coding!
