Send form data received in the backend to the database (MongoDB)

How to send form data from the backend-to the database (MongoDB)

In this tutorial we will use the data of the previous tutorial: Send form data to the backend (Node JS).

If you did not read this tutorial you can check it here : https://purpose-code.com/send-form-data-to-the-back-end-node-js/

Also, we will use MongoDB as database to store data. To know more about MongoDB and how to set it up and get the link to establish a connection check this tutorial: https://purpose-code.com/send-data-from-backend-node-js-to-mongodb/

So, to store form data in the database, let’s follow the below steps:

serter-version="2">

1)- Step 1: Create a template

First, let’s create a template of our data.

>

A template is simply a model to tell MongoDB that the data should be stored in a certain way.

d-placeholder-121" data-inserter-version="2">

To create a template or a model for our data we will use mongoose.

mongoose is an Object Data Modeling library for MongoDB and Node JS. It is this library that manages relationships between data.

So to install it all you have to do is to go to Node JS terminal and type: npm install mongoose.

mongoose installation

Once installed create a template.js file.

Inside this template.js file we will import the mongoose package by requiring it. So the code will be:

requiring mongoose package

mongoose works with a Schema constructor. It is this Schema constructor that allows us to set a template for our data.

To access the Schema constructor we’ll use the following code:

Schema constructor

So now we will create an instance of this constructor and set our template:

Data template

Here we told mongoose that we want the data to be stored with the variable userName holding the name of the user, the variable userEmail holding the email of the user, the variable userMessage holding the message of the user and then variable createdAt that will save the date when the data is added to the database.

Also we added some validations like for the message, it should not exceed 20 characters, so we set the maxLength to 20. And for the date, we want the date to be the date of today, hence the default property set to Date.now().

For the variables name userName, userEmail and userMessage they should be the same as the attribute name in the From:

name attribute

Now that we set our template, all what is left is to tell mongoose to generate a model from the created template.

To do that we’ll add the code:

Model generated

mongoose.model() syntax allows us to create a model, and takes 2 parameters. The first parameter is the name of the collection where we want our data to be stored, and the second parameter is the template that we set and that mongoose will use to create the model from.

Finally, we have to import the dataModel so that we can use it outside the template.js file.

dataModel exported

2)- Step 2: Store data in MongoDB

After setting a templating for our data, now it is time to send to the database and store it there.

To do that we will go back to the index.js file.

we will require mongoose again as it will help us establish a connection to MongoDB.

We will also require the template.js module.

So the code will be:

requiring mongoos and template.js

And then we will connect to the database.

To do that go to MongoDB, and click on the connect button below:

Connect button

Click on the “connect your application”:

Connect application

Copy the link that you will have :

Link generated

And then store this link in a variable that we’ll call dbURI:

Link stored

Here in the link change the <username> tag, add the name of someone who has the rights to access the database instead. In this example it is Tim.

And also in the <password> tag, add the password of someone who has the rights to access the database, in this example it is Tim’s password which is 123.

For more information on how to connect to MongoDB check my tutorial : https://purpose-code.com/send-data-from-backend-node-js-to-mongodb/

Now let’s connect to MongoDB. For that we’ll use mongoose and the code will be:

Connecting to MongoDB

mongoose.connect() syntax is an asynchronous syntax, that’s why we have then() and catch() methods.

mongoose.connect() takes the URL we stored in dbURI variable to connect to as a parameter, and an object that should be added to avoid any Node JS deprecation or error messages.

So now in the app.post() method instead of just displaying the received data in Node JS terminal as we did in the previous tutorial: https://purpose-code.com/send-form-data-to-the-back-end-node-js/ , we want to send data to MongoDB.

To do that we will add an asyncronous function where we will create a new variable:

storing data to database

Inside this variable which is newData we stored the userForm.create(req.body) value.

userForm.create() is here to create the the data received in MongoDB.

The body is the body that the form sends when clicked on the submit button. This body contains the data we want to store, and to access it in the backend we use the req.body syntax.

So the final code becomes:

Server side code

Now if we go to the browser and add some information in the form:

Form completed

And click the send button, in Node JS terminal we will run the server, and go to MongoDB and refresh the page and we’ll have:

Data added to MongoDB

So now the data is stored in the “users” collection we created in template.js file.

index.html code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>HTML form</title>
    <style>
        label{
            width:100px;
            display:inline-block;
            margin-top:10px;
            margin-bottom:20px;
        }
        .textarea,#message{
           vertical-align:top;
        }
        
        #button{
            margin:20px 0px 0px 100px;
            width:100px;
            padding:5px;
            background-color:blueviolet;
            color:white;
        }

    </style>
</head>
<body>
    <form action="/contact" method="POST">
        <label for="fullName">Full Name: </label><input type="text" id="fullName" name="userName"/><br/>
        <label for="emailAddress">Email: </label><input type="email" id="emailAddress" name="userEmail"/><br/>
        <label for="message" class="textarea">Message:</label><textarea cols="30" rows="10" id="message" name="userMessage"></textarea><br/>
        <input type="submit" value="Send" id="button"/>
    </form>
</body>
</html>

index.js code:

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

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

app.use(express.urlencoded({ extended: true }));

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

app.post("/contact", (req, res) => {

    async function createData() {
        var newData = await userForm.create(req.body);
    }
    createData();
})

template.js code:

var mongoose = require(“mongoose”);

var UserForm = mongoose.Schema;

var userData = new UserForm({

    userName: String,

    userEmail: String,

    userMessage: {

        type: String,

        maxLength: 20

    },

    createdAt: {

        type: Date,

        default: () => Date.now()

    }

});

var dataModel = mongoose.model(“users”, userData);

module.exports = dataModel;

1 thought on “Send form data received in the backend to the database (MongoDB)”

  1. This blog is a rich source of information and knowledge about the latest MERN stack development technologies including MongoDB and React.js. It offers a comprehensive understanding of how these technologies are developed, utilized, and optimized for maximum efficiency.

Leave a Reply

%d bloggers like this: