How to send data from back-end(Node JS) to MongoDB database?

How to send data from back-end to database?

To send data received by the back-end to a database and store it there we’ll use mongoose.

mongoose is a Node JS library for MongoDB database.

In this tutorial we’ll use MongoDB as database.

To know how we send data from the front-end to the back-end check my tutorial:

api-send-data-from-front-end-to-back-end/">https://purpose-code.com/fetch-api-send-data-from-front-end-to-back-end/

1)- What is MongoDB?

MongoDB is a document-oriented NoSQL database used for high volume data storage. The difference be

tween MongoDB and the traditional database like SQL is that MongoDB stores data in collections, while the traditional database store data in tables (rows and columns).

Traditional storage
MongoDB storage

2)- How to send data from Node JS to MongoDB?

Let’s work with the data we had from the previous tutorial that you can check here:

s://purpose-code.com/fetch-api-send-data-from-front-end-to-back-end/" target="_blank" rel="noreferrer noopener">https://purpose-code.com/fetch-api-send-data-from-front-end-to-back-end/

Le’ts store this data in mongoDB.

First let’s install a library in Node JS called mongoose. mongoose will help us set a template of the data to tell MongoDB this is how we want our data to be stored.

To install mongoose just go to Node JS terminal and type npm install mongoose.

mongoose installation

Now that mongoose is installed, let’s create a new .js file.

1)-Step 1: Create a new .js file

Let’s create a new .js file and give it a name of template.js.

Inside this file we’ll import our mongoose library or module. To do that we’ll use the require() syntax.

So the code will be:

require mongoose module

After requiring mongoose module, we’ll access mongoose Schema property. The mongoose Schema property is a constructor. This constructor is what will allow us to set a template for our data.

To access mongoose Schema we’ll add the following code:

Accessing mongoose Schema

The Template variable name starts with uppercase T because as we said, Schema is a constructor, and constructor’s names always start with uppercase.

Now it is time to create the template. To do that we’ll call the Template constructor that will help us create a new instance.

New instance of the Schema object

So inside this dataTemplate variable we’ll add the template of our data to tell mongoose we want MongoDB to receive for example the name, the age and the city of each user, or we want MongoDB to receive the name, the email and the address of each user and so on… Depending on what we want to store.

So here we want to store the name, the email and the city of the users. So the template will be:

Data template

So here we told mongoose that we want to store the name, the email and the city. And also we specified the type of these variables. All the variables are String.

If we wanted to store the phone number as well, and add some condition on the email to make it compulsory for the user to provide it, and the name to be less than 10 characters long, we would have set the template like this:

Data template with more requirements

But now let’s keep it simple and store only the name, city and the email of the users.

Now we will tell mongoose we’re finished, all you have to do is to create the model from the template we just created, and store it in a certain database:

Final Template

mongoose.model() syntax is what tells mongoose to create a model. It takes 2 arguments: The name of the database and the template we created. Which means mongoose should create a model and store it in a database named “user”, and the model should be created from the dataTemplate variable.

Just for information, when storing data in MongoDB, if MongoDB does not find the database that has a name of “user” then it will create one automatically.

Also, here we gave the database a name of “user”, but when storing data MongoDB will add an “s” at the end of the “user”, which will make it “users”. This is how MongoDB works.

So now that we told mongoose to create a model, it is time to export the variable finalTemplate so that we can work with it and use it outside the template.js module.

Exporting finalTemplate variable

2)- Step 2: Connect to the database

Now let’s connect to the database.

First, go to MongoDB and create a free account here: https://www.mongodb.com/cloud/atlas/register

Once the account created the following page will appear:

MongoDB cluster

You should create a “cluster” by clicking on the button “Build a cluster“.

Once clicked on the button you’ll have to choose one of the 3 plans. In this tutorial we’ll go with the “Free” plan.

MongoDB Free plan

Now after choosing the Free plan you’ll have the following page:

Cluster name

Down in the above picture there is “Cluster name” section, click there and give the cluster a name of “nodetuts”. You can give it any name you want but in this tutorial we will work with “nodetuts”.

Now after creating the cluster you’ll have the following page:

MongoDB database

Now that we have a cluster we will create a user password, so that when connecting to the database, only the the person who has the password can connect to it.

For that go the menu bar on the left and click on “Database access”:

Database access

Once clicked the following page appears. Click on the “Add new Database user” button on the right:

Adding a new User

Now you can add the user who can access the database. In this case I will add Tim and give him a password of 123.

User password

To specify and allocate a role to Tim scroll down in the same page to “Built-in Role”:

User role

Then choose one of the roles available. For this tutorial I will give Tim a role of “Read and write any database”. Which means admin.

Then once finished click on the “Add user” button at the the end and you’ll have the following screen:

Tim added to the list of admins

Now let’s go back to the dashboard and click on the “connect” button. To go back to the dashboard just click on “database” on the menu on the left:

Dashboard

Once clicked on “connect” button you’ll have this page:

Options to connect to the cluster

So here MongoDB offers many options to connect to the “nodetuts” cluster that we created. We will choose one option that is “Connect your application”. So click on the “Connect your application” tab.

After clicking you’ll have:

URL

So here mongoDB gives us a URL that we will use in Node JS to connect to the database. Now all you have to do is to copy this URL and go to the index.js file, create a variable with the name of dbURI and paste this URL there.

Also we will require mongoose module and our template.js module. So the code becomes :

URL added to index.js file

Now in this URL, there is a tag that states <username>, and there is another tag that states <password>. That means we should replace those tags with the name of the user we created, which means “Tim”, and the password of “Tim” which is 123.

This way we will connect to the Database via Tim and his password. So the code is:

URL with username and password replaced

Now it’s time to connect to the database. To do that we’ll use mongoose.

Connecting to MongoDB

To connect to MongoDB we use mongoose.connect() syntax. mongoose.connect() is asynchronous that’s why we have then() and catch() methods.

mongoose.connect() takes 2 arguments: the 1st argument is the URL we want to connect to, and the second argument is an object that if you don’t add it Node will tell you to to avoid any errors.

Inside of then() method we add the app.listen(3000) instruction because we don’t want to listen to PORT 3000 before we’re connected to the database, as mongoose.connect() is asynchronous.

The catch() method is here to catch any errors.

3)- Step 3: Send the data to MongoDB

Now that we’re connected to MongoDB we can start sending and storing the data.

To do that we will change the code in the app.post() routing. We will remove the console.log(req.body) and instead we’ll add an async function.

So the code is:

Async await function

Inside the async function we called sendData() we added a variable named userInfo.

This variable is an object that will contain the name, email and city of the user. To get back the name of the user we use req.body.name syntax. Because the name is in the body we sent from the front-end. Same thing for other variables.

we use myData.create syntax to create the data to be sent to MongoDB using the template we created with mongoose.

Now one more thing to do on MongoDB side, go back to MongoDB dashboard and click on “Browse Collections” button:

Browse Collections button

You’ll have the page below. Click on “Add my own data” button:

Add my own data button

Once clicked you’ll have the following page. Add a database name and a collection name:

Databse and collection name

Here we added “MongoTrial” as Database name and “users” as Collection name. This is where MongoDB will store the data.

Click now on “create” button.

So at the end you’ll have:

Database created

You have the name of the Database and Collection on the left.

Now let’s go back to the browser and fill in the inputs with the data.

Let’s say that we have a user, her name is Natalia, her email is natalia@gmail.com and her city is London.

Front-end data

Now let’s click on the “send” button.

Once clicked on the “send” button, go back to MongoDB and refresh the page, you will see the data added to the data base as below:

Data added to Database

However, on the left, you will notice that there is a 2nd database added which has a name of “test”, and it is inside of this database that the “user” collection we added in mongoose template is added now.

This is not what we want. Because we’ve already created a database name which is “MongoTrial” and we want the data to be added in this database, not in “test” database.

So to do that we should simply specify that to MongoDB. And to do that let’s go back to the index.js file, to the dbURI variable that contains the link to the database, and add the name of the database “MongoTrial” between the backslash and the question mark like this:

mongodb+srv://Tim:123@nodetuts.lvalw.mongodb.net/MongoTrial?retryWrites=true&w=majority

So the final code becomes:

Final code

Now if you refresh the browser and enter Natalia’s detail once again and click on the “send” button, and refresh the MongDB website you’ll have:

Data added to the database

Now we have the data added to the database we want and to the collection we created.

index.js file:

var express = require("express");
var app = express();
var mongoose = require("mongoose");
var myData = require("./template");
var dbURI = "mongodb+srv://Tim:123@nodetuts.lvalw.mongodb.net/MongoTrial?retryWrites=true&w=majority";

app.use(express.json());

mongoose.connect(dbURI, { useNewUrlParser: true, useUnifiedTopology: true })
    .then(r => app.listen(3000))
    .catch(e => console.log(e));


app.get("/", (req, res) => {
    res.sendFile("index.html", { root: __dirname });
})

app.post("/api", (req, res) => {
    async function sendData() {
        var userInfo = await myData.create({
            name: req.body.name,
            email: req.body.email,
            city: req.body.city
        })
    }
    sendData();
    res.json({
        message: "It's perfect, I received all the data"
    });
})

template.js file:

var mongoose = require("mongoose");
var Template = mongoose.Schema;

var dataTemplate = new Template({

    name: String,
    email: String,
    city: String,

});

var finalTemplate = mongoose.model("user", dataTemplate);

module.exports = finalTemplate;

Get new content delivered directly to your inbox

Leave a Reply

%d bloggers like this: