DEV Community

Cover image for I've created a CRUD server with docker, fastify and mongoDB
Simone Gentili
Simone Gentili

Posted on • Edited on

I've created a CRUD server with docker, fastify and mongoDB

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 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.

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

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

Create

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

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
    })
})
Enter fullscreen mode Exit fullscreen mode

Read

I want to list all books stored in database.

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

    reply.send(books)
})
Enter fullscreen mode Exit fullscreen mode

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.

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
    })
})
Enter fullscreen mode Exit fullscreen mode

Delete

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)
})
Enter fullscreen mode Exit fullscreen mode

Server

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

start()
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)