Premise
The following is the code explained in my youtube video (italian only, .. but eng subtitled) that is scheduled for 02-02-2023.
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.
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'
})
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
})
})
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)
})
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
})
})
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)
})
Server
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
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/ -d ‘{“Title”:”Node.js Design Patterns”, “Authors”:[“Mario Casciaro”, “Luciano Mammino”]}’
- curl -v -X DELETE http://localhost:3000/books/