So, to store form data in the database, let’s follow the below steps:
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.
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.
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:
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:
So now we will create an instance of this constructor and set our 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:
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:
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.
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:
And then we will connect to the database.
To do that go to MongoDB, and click on the connect button below:
Click on the “connect your application”:
Copy the link that you will have :
And then store this link in a variable that we’ll call dbURI:
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.