Store and Retrieve Data with Node.js, Express and MongoDB

First of all, in order to create your first server, you need to have Node.js and npm installed on your machine. You can search the web for instructions on how to install them on your preferred platform or visiting the official web site (consider that npm comes with Node).

These are the versions I used in this story building the project

  1. Node.js v12.10.0
  2. npm v6.9.0

Let’s start!

Through the command-line, create a main folder for your project, go into, and execute

npm install express

It installs the Express Framework able to start Node.js applications, making node_modules directory and package-lock.json file.

Let’s create, in the root path of the main folder, a file called app.js…

touch app.js

and write the following lines of code.

let express = require(‘express’);

let app = express();

app.listen(3000, () => console.log(‘Server running on port 3000!’))

Finally, let’s execute

node app.js

to start the server.

Hence, you should read

Server running on port 3000!

It sounds great! You have set up your first server in Node.js and Express.

Handle first HTTP requests

Now that you’ve managed to configure the server, let’s take a look at how to handle the GET and POST requests that return, respectively, the route parameter or body provided in the input.

Handle the GET request

app.get(‘/:name’, (req, res) => {
res.send(‘Your name is ‘ + req.params.name + ‘\n’);
});

In this way, we register a handler for incoming GET requests with name route parameter.

Through req.params.{param_name} we can access directly to the input route parameters.

Restart the server and test the endpoint making a cURL

1. curl ‘http://localhost:3000/John'

2. Output -> Your name is John

Handle the POST request

In order to handle HTTP POST requests, we have to define a middleware that can be used by the server to read JSON payload.

app.use(express.json());

So, we can simply define the handler for the POST request as well as the GET handler declared before.

app.post('/', (req, res) => {
res.json(req.body);
});

Notice how we can get access to the request body reading the body property of the request through req.body

Testing the endpoint through cURL

1. curl -d '{"name": "John", "age": 32}' -H "Content-Type: application/json" -X POST http://localhost:3000

2. Output -> {"name": "John", "age": 32}

Setting up MongoDB

Now, it’s time to store our data in a MongoDB database!

Download MongoDB from the official download web page.

Update local machine environment variables through the command

echo "export PATH=$PATH:/mongo-dir/bin" >.bash_profile

Obviously, replace “mongo-dir” with the main path of your previously unzipped folder.

Open two terminal windows. In the first, run the ./mongod instance, in the other one the ./mongo shell.

In this way, we have started the MongoDB instance locally.