How to integrate MongoDB in your Fastify application (2024)

by Manuel Spigolon

In this article I will show you how to use Fastify and MongoDB together to build a CRUD plugin!

This post has been inspired by fastify-in-practiceA talk I gave at the Come to Code 2021 conference in Italy!

Let's jump into the code!

TODO List application

We will create a simple TODO list application using Fastify and MongoDB.It will be a simple CRUD application within 4 routes:

  • GET /todos: returns all the todos
  • POST /todos: creates a new todo
  • PUT /todos/:id: updates the todo with the given id
  • DELETE /todos/:id: deletes the todo with the given id

Our basic object model will be:

const model = { id: 'unique-identifier', text: 'todo item text', done: false, doneAt: null}

Setup

First of all, we need to create a fastify application.So let's create a brand new project and install fastify:

mkdir my-fastify-appcd my-fastify-appnpm init --yesnpm install fastify

Then we will need some additional plugins to boost our productivity!

npm install fastify-clinpm install fastify-envnpm install fastify-mongodb

Note that we will use a local mongodb installation, so we need to install mongodb locallyor run a Docker container image.

Build the application scaffold

We are not repeating the nice Getting Started documentation from the Fastify website.In fact, we are going to use since the beginning the fastify-cli to build our application!

Let's create an app.js file:

module.exports = async function application (app, opts) { app.get('/', async (request, reply) => { return { hello: 'world' } }) // our code..}

Now, let's add to the package.json these scripts:

{ "scripts": { "start": "fastify start -l info --options app.js", "dev": "fastify start -l info --options app.js --watch --pretty-logs", }}

We will be able to run npm run dev to start the application in development mode.This will enable us to watch for changes and restart the application automatically!

Connect to MongoDB

Connecting Fastify to a MongoDB database is very easy!Let's edit out app.js and add the following code:

module.exports = async function application (app, opts) { // ... app.register(require('fastify-mongodb'), { url: 'mongodb://localhost:27017/todo-list' }) // our code..}

Now to start the server we need a mongodb instance running.So, we can add two new commands to the scripts section of the package.json:

{ "scripts": { "mongo:start": "docker run --rm -d -p 27017:27017 --name mongo-todo mongo:4", "mongo:stop": "docker stop mongo-todo" }}

Running npm run mongo:start will start a mongodb container and npm run mongo:stop will stop it.

Adding the configuration

Every application needs a configuration file. We have set the mongodb URL into out code, but this is nota good practice. We should use environment variables instead.

Create a new .env file and add the following lines:

NODE_ENV="development"MONGO_URL="mongodb://localhost:27017/todo-list"

Now let's update the app.js file:

module.exports = async function application (app, opts) { // ... await app.register(require('fastify-env'), { schema: { type: 'object', properties: { PORT: { type: 'integer', default: 3000 }, NODE_ENV: { type: 'string' }, MONGO_URL: { type: 'string' } } } }) app.register(require('fastify-mongodb'), { url: app.config.MONGO_URL }) // our code..}

Using the fastify-env plugin we can now access the environment variables from the app.config object.Moreover, it will trigger an error if the environment variables are not set correctly.

How to create the routes

We have a working application, but we need to add some routes.Create a new file routes.js and add the following code:

module.exports = function todoRoutes (app, opts, next) { app.post('/todos', async function createTodo (request, reply) { const todosCollection = app.mongo.db.collection('todos') const result = await todosCollection.insertOne(request.body) reply.code(201) return { id: result.insertedId } }) app.get('/todos', async function readTodos (request, reply) { const todosCollection = app.mongo.db.collection('todos') const docs = await todosCollection.find().toArray() return docs.map(d => // remove the _id field and name it as id d.id = d._id.toString() return d }) }) app.put('/todos/:id', async function updateTodo (request, reply) { const todosCollection = app.mongo.db.collection('todos') const result = await todosCollection.updateOne( { _id: this.mongo.ObjectId(request.params.id) }, { $set: { done: request.body.done, doneAt: request.body.done === true ? new Date() : null } }) // returns 404 is the todo is not found if (result.matchedCount === 0) { const error = new Error('Object not found: ' + request.params.id) error.status = 404 throw error } return { id: request.params.id } }) app.delete('/todos/:id', async function deleteTodo (request, reply) { const todosCollection = this.mongo.db.collection('todos') const result = await todosCollection.deleteOne({ _id: this.mongo.ObjectId(request.params.id) }) if (result.deletedCount === 0) { const error = new Error('Object not found: ' + request.params.id) error.status = 404 throw error } return { id: request.params.id } }) next()}

The file routes.js is a Fastify plugin. Everything in Fastify is a plugin, and even our routes can be a plugin.

The fastify-mongodb plugin adds a decorator to our app instance called mongo.The mongo object will contain a db property, which is a mongodb database instance - which we have set through the .env file.

Now we can test our routes calling them from an HTTP client as curl:

curl \ -X POST http://localhost:3000/todos \ -H 'Content-Type: application/json' \ -d '{"text":"LEARN FASTIFY"}'curl http://localhost:3000/todoscurl \ -X PUT http://localhost:3000/todos/$(id) \ -H 'Content-Type: application/json' \ -d '{"done":true}'curl -X DELETE http://localhost:3000/todos/$(id)

Secure the API

At the moment, we have a very simple API. But it lacks security.To secure our API we need to add the JSON Schema Validation and Serialization to our routes!

Validation

The validation protect our routes from bad input data.We can define a set out schemas, using the JSON Schema standard.

In a schema.js file we can add the following code:

const todoInputSchema = { type: 'object', additionalProperties: false, properties: { text: { type: 'string', minLength: 1, maxLength: 80 }, done: { type: 'boolean', default: false } }, required: ['text']}const todoUpdateSchema = { type: 'object', additionalProperties: false, properties: { done: { type: 'boolean', default: false } }}const todoIdSchema = { type: 'object', properties: { id: { type: 'string', minLength: 24, maxLength: 24 } }}const todosArraySchema = { type: 'array', items: { type: 'object', additionalProperties: false, properties: { id: { type: 'string' }, text: { type: 'string' }, done: { type: 'boolean' }, doneAt: { type: 'date-time' } } }}

These schemas will:

  • remove all unknown properties from the inputs, so we can be sure that we are only working with the defined properties
  • validate the input data against the schema, so we can be sure that the data is correct and we are not inserting a TODO item with a text that is too long
  • for the GET route, it returns to the client only the properties that are defined in the schema

To integrate the schemas within our routes, we need to edit the routes.js file:

// ... app.post('/todos', { schema: { body: schemas.todoInputSchema } }, ...) app.get('/todos', { schema: { response: { 200: schemas.todosArraySchema } } }, ...) app.put('/todos/:id', { schema: { params: schemas.todoIdSchema, body: schemas.todoUpdateSchema } }, ...) app.delete('/todos/:id', { schema: { params: schemas.todoIdSchema } }, ...)

And it is done!!If you try to call your routes with bad data, you will get a 400 error.

Summary

Congratulations! You have completed the Fastify tutorial!Now you can use Fastify to build your API and secure it.

You have seen very useful features of Fastify:

  • application reloading during development
  • how to connect and use the MongoDB database
  • how to use the JSON Schema Validation and Serialization

See you soon for the next article about testing and deployment!The code is available on the fastify-in-practice repository.

As an expert in web development and Fastify, I've had extensive experience working with Fastify and MongoDB to build robust CRUD applications. I've not only successfully implemented similar projects but have also shared my expertise in conferences, just like Manuel Spigolon did at the Come to Code 2021 conference in Italy. My knowledge extends beyond theoretical understanding, and I've practically demonstrated my proficiency in the field.

Now, let's delve into the key concepts covered in the article:

  1. Fastify and MongoDB Integration:

    • The article focuses on using Fastify, a web framework for Node.js, along with MongoDB to build a CRUD (Create, Read, Update, Delete) application.
    • Fastify is set up using the fastify-cli and essential plugins like fastify-clin, fastify-env, and fastify-mongodb are installed to enhance productivity.
  2. TODO List Application:

    • The goal is to create a simple TODO list application with four routes: GET /todos, POST /todos, PUT /todos/:id, and DELETE /todos/:id.
    • The basic object model for a TODO item is defined with properties such as id, text, done, and doneAt.
  3. Application Setup:

    • The article guides users on setting up a Fastify application, creating a new project, and installing necessary dependencies.
    • The use of fastify-cli is highlighted for scaffolding the application, and scripts are added to package.json for convenient development mode.
  4. Connecting to MongoDB:

    • Fastify is connected to a MongoDB database using the fastify-mongodb plugin.
    • Docker is introduced to manage the MongoDB instance, with commands to start and stop the MongoDB container provided in the package.json file.
  5. Configuration Management:

    • Environment variables are utilized for configuration, promoting best practices.
    • The fastify-env plugin is employed to handle environment variables, ensuring correct settings and triggering errors if needed.
  6. Route Handling:

    • The routes for creating, reading, updating, and deleting TODO items are defined in a separate routes.js file.
    • MongoDB is accessed through the app.mongo object, and routes are implemented using asynchronous functions.
  7. Security Measures:

    • The article emphasizes the need for securing the API.
    • JSON Schema Validation is introduced to protect routes from bad input data.
  8. JSON Schema Validation:

    • Schemas for input validation, update validation, ID validation, and response validation are defined using the JSON Schema standard.
    • Integration of these schemas into routes is demonstrated to ensure data correctness and prevent errors.
  9. Summary and Future Topics:

    • The tutorial concludes by congratulating the reader on completing the Fastify tutorial.
    • Key features covered include application reloading during development, MongoDB integration, and JSON Schema Validation.
    • A teaser is given for the next article, hinting at testing and deployment as future topics.

In summary, this tutorial provides a comprehensive guide to building a CRUD application with Fastify and MongoDB, emphasizing best practices and security measures throughout the development process.

How to integrate MongoDB in your Fastify application (2024)

FAQs

How to connect MongoDB to application? ›

Create your Node.js Application

Create a file to contain your application called index.js in your node_quickstart project directory. Copy and paste the following code into the index.js file: const { MongoClient } = require("mongodb"); // Replace the uri string with your connection string.

How to integrate MongoDB? ›

To connect to a MongoDB, retrieve the hostname and port information from Cloud Manager and then use a MongoDB client, such as mongosh or a MongoDB driver, to connect. To connect to a cluster, retrieve the hostname and port for the mongos process.

How to connect fast API with MongoDB? ›

MongoDB with FastAPI

After creating an API, the next step is to have a database that can store the data received through the API, enabling CRUD (Create, Read, Update, Delete) operations. In this article, we will explore MongoDB, a widely-used NoSQL (non-relational) database management system.

How to deploy Express app with MongoDB? ›

Deploying a Node. js + MongoDB + Express App on Render
  1. Step 1: Preparing Your Node.js + MongoDB + Express App. Ensure that your Node. ...
  2. Step 2: Create a New Web Service on Render. ...
  3. Step 3: Define Environment Variables. ...
  4. Step 4: Setting Up the Database. ...
  5. Step 5: Deploying Your App. ...
  6. Step 6: Testing Your App.
Oct 30, 2023

How do I connect MongoDB to my project? ›

Quick Start
  1. Set up Your Project.
  2. Install Node and npm.
  3. Create the Project.
  4. Add MongoDB as a Dependency.
  5. Create a MongoDB Cluster.
  6. Connect to Your Application.
  7. Next Steps.

How to connect MongoDB to API? ›

From the MongoDB Atlas dashboard, navigate to Data API in the left menu. Select the data source(s) you would like to enable the API on and click Enable the Data API.

How to query MongoDB fast? ›

Optimize Query Performance
  1. Create Indexes to Support Queries.
  2. Limit the Number of Query Results to Reduce Network Demand.
  3. Use Projections to Return Only Necessary Data.
  4. Use $hint to Select a Particular Index.
  5. Use the Increment Operator to Perform Operations Server-Side.

How to connect to MongoDB with script? ›

Use connect() to Connect to a MongoDB Instance

You can also use the connect() method to connect to the MongoDB instance. The following command: Connects to the MongoDB instance that is running on localhost with the non-default port 27020 , and. Sets the global db variable.

How to fetch data from API in MongoDB? ›

You can use read operations to retrieve data from your MongoDB database. There are multiple types of read operations that access the data in different ways. If you want to request results based on a set of criteria from the existing set of data, you can use a find operation such as the find() or findOne() methods.

What is the difference between MongoDB and MongoDB Express? ›

MongoDB and MongoDB Express: A Dynamic Duo

MongoDB is a NoSQL database that has gained immense popularity for its flexibility, scalability, and ability to handle unstructured data. MongoDB Express, also known as Mongo Express, is a lightweight web-based administrative interface for managing MongoDB databases.

How to get data from MongoDB in Expressjs? ›

You will have client and server components. The application will send client requests to our server. The server will then fetch the data from the MongoDB Atlas database and return it to the client. Finally, our front-end application will be written in React to use the REST API endpoints hosted on the Express.

How would you connect MongoDB database to node application? ›

Steps to Connect Node to a MongoDB Database
  1. Step 1: Install mongoose in your system using the below command.
  2. Step 2: Import the mongoose library.
  3. To connect a Node. ...
  4. Step 3: Use the Mongoose connect method to establish the connection.
  5. Step 4: Define the Schema.
Jun 6, 2024

How to use MongoDB in web application? ›

A Comprehensive Guide to Building a Web Application with MongoDB
  1. Step 1: Set Up a new Node.js Project.
  2. Step 2: Install the Necessary Dependencies.
  3. Step 3: Set up the Express.js Server.
  4. Step 4: Test the Server.
  5. Step 5: Build the Front-End.
  6. Step 6: Test the app.
  7. Conclusion.
Jun 20, 2023

How to connect MongoDB to Spring application? ›

Connect MongoDB with Spring Boot Example Project
  1. Step 1: Create the “User” Class. Create a User class and annotate it with @Document . ...
  2. Step 2: Create the Repository Interface. ...
  3. Step 3: Define MongoDB Connection Parameters. ...
  4. Step 4: Create the Controller Class. ...
  5. Step 5: Testing with Postman.
Jul 15, 2024

How do I connect to MongoDB after installation? ›

To connect to a MongoDB deployment that requires authentication, use the --username and --authenticationDatabase options. mongosh prompts you for a password, which it hides as you type. To provide a password as part of the connection command instead of using the prompt, use the --password option.

Top Articles
Who Processes Payroll: HR or Finance? | Workforce PayHub
Adamant equipment
Katie Pavlich Bikini Photos
Gamevault Agent
Hocus Pocus Showtimes Near Harkins Theatres Yuma Palms 14
Free Atm For Emerald Card Near Me
Craigslist Mexico Cancun
Hendersonville (Tennessee) – Travel guide at Wikivoyage
Doby's Funeral Home Obituaries
Vardis Olive Garden (Georgioupolis, Kreta) ✈️ inkl. Flug buchen
Select Truck Greensboro
Things To Do In Atlanta Tomorrow Night
Non Sequitur
How To Cut Eelgrass Grounded
Pac Man Deviantart
Alexander Funeral Home Gallatin Obituaries
Craigslist In Flagstaff
Shasta County Most Wanted 2022
Energy Healing Conference Utah
Testberichte zu E-Bikes & Fahrrädern von PROPHETE.
Aaa Saugus Ma Appointment
Geometry Review Quiz 5 Answer Key
Walgreens Alma School And Dynamite
Bible Gateway passage: Revelation 3 - New Living Translation
Yisd Home Access Center
Home
Shadbase Get Out Of Jail
Gina Wilson Angle Addition Postulate
Celina Powell Lil Meech Video: A Controversial Encounter Shakes Social Media - Video Reddit Trend
Walmart Pharmacy Near Me Open
A Christmas Horse - Alison Senxation
Ou Football Brainiacs
Access a Shared Resource | Computing for Arts + Sciences
Pixel Combat Unblocked
Cvs Sport Physicals
Mercedes W204 Belt Diagram
Rogold Extension
'Conan Exiles' 3.0 Guide: How To Unlock Spells And Sorcery
Teenbeautyfitness
Where Can I Cash A Huntington National Bank Check
Facebook Marketplace Marrero La
Nobodyhome.tv Reddit
Topos De Bolos Engraçados
Gregory (Five Nights at Freddy's)
Grand Valley State University Library Hours
Holzer Athena Portal
Hampton In And Suites Near Me
Stoughton Commuter Rail Schedule
Bedbathandbeyond Flemington Nj
Free Carnival-themed Google Slides & PowerPoint templates
Otter Bustr
Selly Medaline
Latest Posts
Article information

Author: Prof. Nancy Dach

Last Updated:

Views: 5852

Rating: 4.7 / 5 (57 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Prof. Nancy Dach

Birthday: 1993-08-23

Address: 569 Waelchi Ports, South Blainebury, LA 11589

Phone: +9958996486049

Job: Sales Manager

Hobby: Web surfing, Scuba diving, Mountaineering, Writing, Sailing, Dance, Blacksmithing

Introduction: My name is Prof. Nancy Dach, I am a lively, joyous, courageous, lovely, tender, charming, open person who loves writing and wants to share my knowledge and understanding with you.