You know Javascript ? Store stuff with a database 💽

Your server died 😭 Use a database to persist your data !

In the #week3-day1 at MentorLéo, we built a simple server that says hi 🙌

Week 3 — Day 2

Let’s understand what a database is, and how to interact with it.

Inside your Node.js server you use variables that exist within a specific context. If the server shuts down and then goes back up you loose the previous state of your variables.

Databases are here to persist your data.

They are 2 big groups of databases that behave differently:

  • SQL based (mySQL, postgreSQL, etc): you must define and use a “schema” of your data. That’s a skeleton that imposes the format of your data.
  • NoSQL (redis, elastic search, mongoDB, etc): without schema. You can store data that doesn’t respect any strict format, but it can be harder to manipulate.

Choosing a database needs an advanced background, it depends on many things (scalability needed for your system, type of your data, how fast do you need to fetch / write it, etc).

MongoDB

Today, we’ll be using MongoDB because it’s easy to use and understand 😎

Follow this installation guide:

In short:

  • install mongoDB
  • install the mongoDB driver for Node.js
  • run the database using mongod

You can tell mongoDB to store the database anywhere you want. Specify a dbpath parameter when launching mongoDB (I use ~/data/db, default is /data/db):

mongod --dbpath <path to data directory>

Keep it running in a terminal to use mongoDB. If you stop it (Ctrl+C) you’ll only stop the database server. Your data will persist, and will be available when you run mongod again 🙌

How things will interact

  • on the left: a terminal (or your browser) sends a GET request on a route:
curl localhost:8080/pop/ip
  • in the middle, the app you code will handle this request and execute operations on the database to perform what’s needed. To do that, your Node.js app will talk with the MongoDB Driver.
  • This driver will talk to the MongoDB server (mongod) on the right for you to make the operations easy. The MongoDB server handles and persist your data.
  • Every MongoDB operation is asynchronous. When your Node.js app have a result for the database operation it requested, it sends a response to the HTTP client (the terminal or the browser):
{"ip":"92.237.136.220"}

How MongoDB works

MongoDB uses JSON documents that are organized in collections (a list of JSON documents). There’s no validation of the JSON document you insert (there’s no schema unlike SQL). Be aware of what you insert.

All you need to know for a beginning are C R U D operations:

  • Create documents (insert them)
  • Read documents (find them using various criterias)
  • Update documents (change their data)
  • Delete documents

Below here’s the minimal code to have an express server running with mongoDB with one route that adds documents:

Once mongod and your Node.js server is running (see previous day if you forgot how to launch it). Then go to your browser at http://localhost:8080/insert or:

curl localhost:8080/insert

Exercise

Now that you know how to add documents, your job is to learn how to do the other operations 💪

Build the following routes (use the route parameters from previous day):

  • GET /jobs : should return all the documents in the response
  • GET /jobs/{company} : where company is a string (like /get/ACME), should return the document matching the given company
  • PATCH /jobs/{company} : adds a field {updated: true} to the documents matching the given company. This is just to train you to add a field to an existing document
  • DELETE /jobs/{company} : deletes all the documents matching the given company

You can use this documentation to help you: https://mongodb.github.io/node-mongodb-native/2.2/quick-start/quick-start/

The GET, PATCH and DELETE are HTTP verbs. By default any HTTP request is a GET request (in curl and your browser). You can specify a custom verb in curl like this:

curl --request PATCH localhost:8080/jobs

Bonus exercise

Make the GET /insert route be POST /jobs. You’ll let the user create a job by letting him give a title/company attribute.

curl --header "Content-Type: application/json" --request POST --data '{"title":"my title","company":"ACME"}' localhost:8080/jobs

Warning: only allow the user to specify title/company. Any other attribute must not be inserted in DB (this could lead to potential security problems).

Hint: you’ll have to install the body-parser module. It parses JSON data passed with POST, PATCH and PUT requests. Use it like this:

const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
app.post('/jobs', function (req, res) {
console.log(req.body);
  // INSERT YOUR CODE HERE
  res.send('OK');
});

In day 3, you’ll learn to put your Node.js and database online !

→ click here to go to Day 3👍

Call to action

Join us and get help from professional mentors !

Apply here, it will always be free ♥ https://mentorleo.co

Like what you read? Give Damien BRY a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.