DEV Community

Cover image for How to create a server with Node, Fastify and MongoDB
Deotyma
Deotyma

Posted on

How to create a server with Node, Fastify and MongoDB

Fastify is more and more popular and more performant than Express. I decide to learn Fastify to use it in a real project. All information about Fastify, you can find here

1) I create a directory fastifyBooks

mkdir fastifyBooks
cd fastifyBooks
npm init
Enter fullscreen mode Exit fullscreen mode

2) When npm is initialized I can install fastify:

npm i fastify
Enter fullscreen mode Exit fullscreen mode

3) It's time to create directory src in fastifyBooks and there I create my entry file app.js Here I will write my server.

mkdir src
cd src
touch app.js
Enter fullscreen mode Exit fullscreen mode

4) Now I can use festify and I create a server in app.js

import Fastify from 'fastify'


const fastify = Fastify({
  logger: true
})


fastify.get('/', function (request, reply) {
    reply.send({ hello: 'world' })
  })


fastify.listen(3000, function (err) {
    if (err) {
      fastify.log.error(err)
      process.exit(1)
    }
    else{
        console.log("server is on port 3000")
    }
})

Enter fullscreen mode Exit fullscreen mode

In this file, I use ES6 not CJ so I have this error when I want to start a server:

SyntaxError: Cannot use import statement outside a module
Enter fullscreen mode Exit fullscreen mode

So I fix a bug, in package.json I put this line of code:

"type": "module",
Enter fullscreen mode Exit fullscreen mode

And now my server works:

working server

5) But I want also MongoDB in my little project so I install it:

npm install mongoose
Enter fullscreen mode Exit fullscreen mode

6) In the directory fastifyBooks I create a directory config where I will put the file db.js

mkdir config
cd config
touch db.js
Enter fullscreen mode Exit fullscreen mode

7) And I write a function to connect DB with server:

import mongoose from 'mongoose'
const db = "databaseàmoi";
const passwordDb="monpass"
const URI =`mongodb+srv://Deotyma:${passwordDb}@cluster0.uncn9.mongodb.net/${db}?retryWrites=true&w=majority`;


const MongoDBbooks = {
    initialize: () => {
        try {
            const client = mongoose.connect(URI, 
                { 
                    useNewUrlParser: true, 
                    useUnifiedTopology: true
                })


            client.then(() => {return console.log(`successfully connected to DB: ${db}`)})
            .catch((err)=> {console.log(err)})
        } catch(err) {
             throw Error(err)
        }
    }
}


export default MongoDBbooks;
Enter fullscreen mode Exit fullscreen mode

7) Now I need to import it to app.js:

import MongoDBbooks from '../config/db.js';
Enter fullscreen mode Exit fullscreen mode

the path is very important.

And now when I need to modify function witch run a server like that:

const start = async()=>{
    try{
        fastify.listen(3000);
        MongoDBbooks.initialize();
    }
    catch(error){
        fastify.log.error(err)
        process.exit(1)
    }
}
start();

Enter fullscreen mode Exit fullscreen mode

At the same moment, I start a server and I initialise a connection with DB.

Now my application is ready for routes.

Top comments (3)

Collapse
 
mk0wan profile image
Victor Mk

Man thanks this ticks all nhe basics very well will definitely find more ways to improve thi cobe, but from now on this mill be my go to approach.

Some improvements:

  1. Gracefully shutting down the fastify server
  2. Implementation of a simple crud function
Collapse
 
ohbob profile image
Roberts Ozoliņš

the example isn't bringing much to the table. More extensive real world example could be more beneficial.

Collapse
 
deotyma profile image
Deotyma

I'm sure you can do better, so I am waiting with impatience for your post with real-world examples that will be more beneficial.