Understanding about Fastify and MongoDB.

Edison Devadoss
3 min readJun 23, 2019

--

In this article, I will explain about Fastify and MongoDB. Fastify is the node framework.

What is node js

Node.js is an open source server environment. Node.js allows you to run JavaScript on the server.

What is Fastify

Fast and low overhead web framework, for Node.js

Fastify is a web framework highly focused on providing the best developer experience with the least overhead and a powerful plugin architecture. It is inspired by Hapi and Express and as far as we know, it is one of the fastest web frameworks in town.

How do we set up in our project:

mkdir fastify-api
cd fastify-api
mkdir src
cd src
touch index.js
npm init

Install the plugin which we need for node.

npm install fastify mongoose nodemon

In this article, I will not explain about Mongo DB.

nodemon

nodemon is the tool for node .js development. It restarts our application automatically.

You need to make the following changes in the package.json file.

“start”: “./node_modules/nodemon/bin/nodemon.js ./src/index.js”

In this article, I will CRUD operation using the fastify framework.

Make initial changes in index.js

const fastify = require('fastify')()// Declare a route
fastify.get('/', async (request, reply) => {
return { hello: 'world' }
})
// Run the server!
const start = async () => {
try {
await fastify.listen(3000)
fastify.log.info(`server listening on ${fastify.server.address().port}`)
} catch (err) {
fastify.log.error(err)
process.exit(1)
}
}
start()

Run your npm.

npm start

Open your browser run this URL http://localhost:3000/ it return {hello: world}.

We need to install MongoDB in your machine. Below the video is helpful to install MongoDB in your machine.

Once you installed MongoDB successfully then run this code.

mongod

Connect your DB.

const mongoose = require(‘mongoose’);mongoose.connect(‘mongodb://localhost/mycargarage’).then(()=>{
console.log(‘MonogoDB Connected…’)
}).catch((error)=>{
console.log(‘error is’, error);
})

In the above, we require Mongoose and connect to our MongoDB database. The database is called mycargarage and if all went well, you will now see MongoDB connected... in your terminal.

Write mongoose schema

const mongoose = require(‘mongoose’);const carSchema = new mongoose.Schema({
title: String,
brand: String,
price: String,
age: Number,
services:{
type: Map,
of: String
}
})
module.exports = mongoose.model(‘Car’, carSchema);

The above car schema code all the information related to our cars.

Create a car controller

//Import our Controllersconst carController = require('../controllers/carController');const routes = [
{
method: 'GET',
url: '/api/cars',
handler: carController.getCars
},
{
method: 'GET',
url: '/api/cars/:id',
handler: carController.getSingleCar
},
{
method: 'POST',
url: '/api/cars',
handler: carController.addCar
},
{
method: 'PUT',
url: '/api/cars/:id',
handler: carController.updateCar
},
{
method: 'DELETE',
url: '/api/cars/:id',
handler: carController.deleteCar
}
]
module.exports = routes;

In the above code, We use different methods GET, POST, PUT and DELETE.

GET — used to getting the data from the server.

POST — used to post the data from the server.

PUT — used to update server data.

DELETE — used to delete data from server.

Update in your index.js

const routes = require('./routes');//Loop over each route
routes.forEach((route, index)=> {
fastify.route(route);
})

Then run your application.

I used postman for testing API.

Thank you for reading this.

Have a nice day!

--

--

Edison Devadoss
Edison Devadoss

Written by Edison Devadoss

Software Engineer / Full Stack Developer / JavaScript / React / React Native / Firebase / Node.js / Book Reader

Responses (2)