How to Save Form Data in Mongodb Database using Node.js


 

In this tutorial we will learn how to save data from the Form in Mongodb database using a Node.js app. We will create a simple form in html in front end and use node.js as backend server to post or save the data into mangoose database.

In the previous blog post, we just learned how to submit the form data using javascript, but in this blog we will learn a little advanced concept of saving the form data into a database.

To learn about how to save data from a form in Mongodb database using node.js, you need to have some basic understanding of node.js, mongoose, and html.

1. Creating a Node.js app

Open the command terminal on your computer and type below commands in it.

mkdir sample-app

cd sample-app

npm init -y 

2. Install Dependencies

In order to successfully run our application, we need to install some dependencies as mentioned below:

Mongoose: Mongoose is a Object Data Modelling library for node.js. It helps in object mapping, creating collections, saving and retrieving the data from MongoDb. EJS is embedded javascript template that is used to embed javascript code in the html. When we generate html, the javascript code is generated along with it. Body-parser is a Node.js middleware that parses the incoming request bodies and extracts vital information from them which you can use to perform various operations. Express is a Node.js framework useful to build web applications.

Use below command to install these dependencies:

npm install mongoose body-parser express ejs

3. Connect to MongoDB

Create a file db.js in the app root directory and paste the below code in it.



4. Creating a Mongoose Schema to Store User Details

Mongoose Schema allows you to define the structure of the document, default values, data types, validators and much more that is used while storing the document inside the collection in mongodb. Create a model.js file and paste the below code in that.


5. Creating an HTML form using EJS as templating engine.

Now we will create an HTML form using EJS as templating engine. EJS is useful in generating HTML markup using simple Javascript. For that we will create a Views folder and in that we will create an index.ejs file. Paste the below code in that. Remember here the method="POST" and action="/add_user" in the form.



6. Adding Routes

Now we will create routes to display the html form that we created and also add create routes to divert the endpoints through which we will receive the form data to the mongodb database. Open index.js and paste below code in that.



7. Execute the project

Add start tag in package.json as shown below.


Run the following command in the terminal:

npm start

if you data gets save in the database, an object will be returned back to  you after submission of the form.


Post a Comment

0 Comments