After reading this tutorial you will know how to create full-stack apps using MERN stack.
MERN is an acronym for web development tech stack consisting of these four technologies:
Let's quickly recall what are these.
Here's a quick recap what are the main technologies used in the MERN stack:
We won't dive deep into details about how to get started with these technologies using MDB GO. Go ahead and check the linked tutorials and once you learn a few things get back here.
If you have enough knowledge to get started, let's do this.
Our example app will be a TODO list. It's a very popular use-case so let's simply get things done one at a time. We will go through the following steps:
todo_app
Let's go!
In order to create a new database you need to run the following command:
$ mdb database init -db mongodb
Now you need to provide your user data and then the database details. Please provide the values of your choice. For example:
? Enter username tony
? Enter password Stark_12
? Repeat password Stark_12
? Enter database name todo_app
? Enter description Database for the TODO app
Note: the password must contain at least one uppercase letter, one lowercase letter, one number, one special symbol and have minimum length of 8.
Hit Enter and it's done.
Please notice that in the command output the username and database name slightly differs from what you provided earlier. Don't worry - it's OK. A few random characters have been added to these values to randomize them and improve security of your database credentials.
Important: Do not close your terminal window until you save your credentials somewhere. This is the only time we will show you your database password. If you don't save it you'll lose it.
That's pretty much it. You can now see how to connect with this database from the Node.js API.
Note: in MongoDB you don't need to create collections before they are used. MongoDB will create a collection when it's first time accessed.
In case you don't know, Mongoose is a MongoDB object modeling tool. It helps managing MongoDB access and models. You can initialize a MDB GO starter that already has configured Mongoose. Simply run the following command:
$ mdb backend init
and choose Express.js + MongoDB API starter
from the list that shows up.
After initialization just go to the newly created project directory and open the
.env
file. After that edit the DB_CONNECTION_STRING
value. You
should paste the connection string that's been shown to you in the previous step. In my
case the updated value looks like this:
DB_CONNECTION_STRING=mongodb://tonye9c88223:Stark_12@mongo.db.mdbgo.com:8604/todo_appbd2f70e0
Save the file and close it.
The starter project is ready to use. You don't have to change anything to run the example app for the sake of this tutorial. Simply publish it using the following command:
$ mdb publish -p node12
After your files get uploaded you can access your app under the address shown in the output.
Note: You may want to check the tutorial where we explain in detail what can go wrong here and how to deal with it.
Note: Since we need to install dependencies and run your app, it may take a few moments until it will be available under the provided URL.
When you open the app URL you will see the default view on the /
endpoint but
when you'll visit /tasks
you will see an empty array indicating that the
tasks
collection has been created and is empty. There are also other
endpoints defined like this:
GET /tasks/:id
POST /tasks
PUT /tasks/:id
DELETE /tasks/:id
These are self-explanatory but if you don't know how to operate on that go and check the tutorial where it is explained.
Alright, only one step left for the fully-working TODO app - React frontend. Let's create it.
We won't show how to create the whole React app here. Instead, you'll learn how to connect to the API assuming you already have a working app.
It's actually pretty easy. All we need to use if JavaScript Fetch API. Let's jump right into it.
First, let's create our state. We are assuming you have the App.js
file where
you want to put API communication logic. Open this file and add the following state
definition:
import React, { Component } from 'react';
class App extends Component {
state = {
tasks: []
}
// ...
}
It's also wise to add apiUrl
field in our class so that we don't have to
repeat it every time:
apiUrl = 'http://express-mongoose-starter.mdbgo.io'; // in your case it will be different
In order to read data from the server we need to make a GET /tasks
request.
You can do it like this:
componentDidMount() {
fetch(`${this.apiUrl}/tasks`)
.then(res => res.json())
.then((data) => {
this.setState({ tasks: data })
})
.catch(console.log)
}
We are utilizing the fetch
function to read tasks from our API and then
setting the state. Creating, updating and deleting tasks is just as easy:
createTask() {
const data = { name: 'Wash the dishes', desc: 'will take a while' };
fetch(`${this.apiUrl}/tasks`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data);
})
.then((res) => res.json())
.then((task) => {
this.setState({ tasks: this.state.tasks.push(task) });
})
.catch(console.log);
}
updateTask() {
const currentTaskId = 1;
const data = { name: 'Wash the dishes', desc: 'will take a while' };
fetch(`${this.apiUrl}/tasks/${currentTaskId}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data);
})
.then((res) => res.json())
.then((task) => {
const oldTask = this.state.tasks.find((t => t.id === currentTaskId));
oldTask.id = updatedTask.id;
oldTask.name = updatedTask.name;
oldTask.desc = updatedTask.desc;
})
.catch(console.log);
}
deleteTask() {
const currentTaskId = 1;
fetch(`${this.apiUrl}/tasks/${currentTaskId}`, { method: 'DELETE' })
.then((res) => res.json())
.then(() => {
const tasks = this.state.tasks.splice(idx, 1);
this.setState({ tasks });
})
.catch(console.log);
}
And that's how you communicate with your API from the React app.