Following from Part 1 and Part 2, we had a working server but the changes are lost when server is restarted π . That sucked, so now time to database the, err ... data! πΎππ₯«
(π₯« <- this is supposed to be a database)
NoSql databases
Compared to SQL databases with tables and rows, NoSql has collections and documents:
Diskdb allows you to use a file-based database with a mongodb-like API. Think SQLite for mongo. But why?
Quick, simple, and fast - no more installation or config files; perfect for whipping a prototype server with some persistence
db is stored along with your code, in regular JSON file, so easy to maintain without extra tooling
No sign-up needed - No more signing up and getting tons of emails
why not?
Very simple with limited API functionality
Really not for Production
For the record, I loved mLab since it was easy, fast and free up to 500MB. But it was recently acquired by MongoDB and replaced with Atlas. I'll make a separate article for a cloud-based DB with Atlas as well.
This effectively creates a connection to the 'data' db, and 'movies' collection.
4. Add a movie to test out connection
// server.js...// add first movieif(!db.movies.find().length){constmovie={id:"tt0110357",name:"The Lion King",genre:"animation"};db.movies.save(movie);}console.log(db.movies.find());
Nice and simple! db.[collection].save(object) to add a document db.[collection].find() to get all current docs
We're only adding this movie if the db is initially empty,
or else we'll end up with lots of Lion Kings with different _ids π¨
π¦π¦π¦π¦π¦π¦π¦
This should give you something like this
Successfully connected to : ./data
[ { id: 'tt0110357',
name: 'The Lion King',
genre: 'animation',
_id: 'fed8db042fac4892bb96fd72ad13290e' } ]
Notice that it added a _id to our item, used as a global id like in mongodb.
5. CRUD to REST to DB
Now that you've seen Create and Read all, here's the complete roundup of the db operations in diskdb syntax for each CRUD - REST route handler.
For details on the REST - HTTP table and route handlers, check out prev post .
Also note that collection here is movies for our example.
CRUD Operation
REST operation
Diskdb Operation
Create
POST /items
db.[collection].save(object)
Read One
GET /items/:id
db.[collection].find(query)
Read All
GET /items
db.[collection].find()
Update
PUT /items/:id
db.[collection].update(query, data, options)
Delete
DELETE /items/:id
db.[collection].remove(query, multi)
6. Changing to diskdb operations
Using the table, we could now replace all of our memory-based operations with the db equivalent.
i. Create β
server.post("/items",(req,res)=>{constitem=req.body;console.log('Adding new item: ',item);// add new item to dbdb.movies.save(item);// return updated listres.json(db.movies.find());});
server.put("/items/:id",(req,res)=>{constitemId=req.params.id;constitem=req.body;console.log("Editing item: ",itemId," to be ",item);db.movies.update({id:itemId},item);res.json(db.movies.find());});
v. Delete β
server.delete("/items/:id",(req,res)=>{constitemId=req.params.id;console.log("Delete item with id: ",itemId);db.movies.remove({id:itemId});res.json(db.movies.find());});
"Okay, that was nice. But what can I do with this? "
β Serving HTML files
β REST API
β Database persistence
Now, this is an actual server for a small project. Add more routes, save some data in the db through API requests. And when you want to reset the db, just reset movies.json to [].
Next up:
(In progress): Using a Cloud DB with Node and Express
This article is part of a Node+Express series I'm working on.
For the meantime, if you can't get enough of Node+Express π€,
checkout my Node workshop (Gihub repo and slides):
Build a server and API for your next web application, using Node, Express and MongoDB
Node workshop
Create a server + REST API for your next web application!
In this workshop, weβll discuss concepts and put them to practice with activities, all about web servers
The code and concepts here would be a great foundation for your next web project
Topics include, but not limited to:
Using Node and Express to build a web server and REST API
Understanding routing, request and response
Implementing CRUD with HTTP methods
Building a server-rendered website using templates
Connecting to a Cloud NoSQL database: MongoDB Atlas DB
User authentication with sessions, cookies and tokens
Using external APIs, such as Github Jobs, Giphy, Spotify