I've created a CRUD server with docker, fastify and mongoDB
Tags: mongodb, fastify
Published: 2023-01-27 12:35:00

---
title: I've created a CRUD server with docker, fastify and mongoDB
published: true
description: Fastify is an amazing node.js framework and mongo is a database I want to start learning
tags: mongodb, fastify, mongo
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hmho8l9r9jredvm07ikv.jpeg
published_at: 2023-01-27 12:35 +0000
series: fastify
---

## Premise

The following is the code explained in my youtube video (italian only, .. but eng subtitled) that is scheduled for 02-02-2023. But if you prefer you can [go to my channel](https://www.youtube.com/@sensorario) ad watch other videos and subscribe so then you will be noticed for all the contents like this one.

You do not need to know how it works docker. But you need to know what is a database. Is not importnat to know the difference between SQL or NoSQL here. It is important to know what a database is. And mongoDB is a database.

## Http calls

At the end of the post all http calls are made with curl. There is also a command called "http". If you prefer you can make same calls with Postman. Use the command or the tool you prefer. If you want, you can also develop your own client with Angular, React or simply html/css/javascript.

## Rest

This post also assumes you knot what is REST. Rest means: Representational State Transfer. Shortly, .. with databases CRUD operations (Create, Read, Update and Delete) have a corresponding http verb.

 - CREATE -> POST
 - READ   -> GET
 - UPDATE -> PUT
 - DELETE -> DELETE

## Package.json

This little fastify CRUD is very very simple. In package json we only have few packages: `@fastify/mongodb@6.0.0` and `fastify`. No other dependencies are required.

## Require

Code here is very very simple. It load fastify ad register mongo. Database is called library just because I wish to build a simple tool to store all my books.

```js
const fastify = require('fastify')({ logger: !true })

fastify.register(require('@fastify/mongodb'), {
    forceClose: true,
    url: 'mongodb://localhost:27017',
    database: 'library'
})
```

## Create

CRUD contains Create, Read, Update and Delete. This is the first letter.

```js
fastify.post('/books', async (request, reply) => {
    const result = await fastify
        .mongo.db.collection('books')
        .insertOne(request.body)

    reply.send({
        message: 'book added',
        id: result.insertId
    })
})
```

## Read

I want to list all books stored in database.

```js
fastify.get('/books', async (request, reply) => {
    const books = await fastify
        .mongo.db.collection('books')
        .find().toArray()

    reply.send(books)
})
```

## Update 

I came from php (Symfony) and see code like `const { bookId } = request.params;` for me is something similar to gold. Node is very nice language. I am falling in love with this language.

```js
fastify.put('/books/:bookId', async (request, reply) => {
    const { bookId } = request.params;
    const ObjectId = fastify.mongo.ObjectId
    const result = await fastify
        .mongo.db.collection('books')
        .replaceOne(
            { _id: new ObjectId(bookId) },
            request.body
        )

    reply.send({
        message: 'book updated',
        id: result.insertId
    })
})
```

## Delete

```js
fastify.delete('/books/:bookId', async (request, reply) => {
    const { bookId } = request.params;
    const ObjectId = fastify.mongo.ObjectId
    await fastify
        .mongo.db.collection('books')
        .deleteOne({ _id: new ObjectId(bookId) })

    reply.statusCode = 204
    reply.send(null)
})
```

## Server

```js
const start = async () => {
    try {
        await fastify.listen({ port: 3000 })
    } catch (err) {
        fastify.log.error(err)
        process.exit(1)
    }
}

start()
```

## Run

Now with two simple commands:

 - `npm run mongo`
 - `npm run start`

we obtain a ready application. In this post I've no clients. So I'll put here some curl commands to make all CRUD operations. Change `<bookId>` with the real id.

 - curl http://localhost:3000/books
 - curl -H 'Content-type: application/json' -X POST http://localhost:3000/books -d '{"Titolo":"Node.js Design PAttern", "Autore": "Luciano Mammino"}'
 - curl -X PUT -H 'Content-type: application/json' http://localhost:3000/books/<bookId> -d '{"Title":"Node.js Design Patterns", "Authors":["Mario Casciaro", "Luciano Mammino"]}'
 - curl -v -X DELETE http://localhost:3000/books/<bookId>