Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • NodeJS Tutorial
  • NodeJS Exercises
  • NodeJS Assert
  • NodeJS Buffer
  • NodeJS Console
  • NodeJS Crypto
  • NodeJS DNS
  • NodeJS File System
  • NodeJS Globals
  • NodeJS HTTP
  • NodeJS HTTP2
  • NodeJS OS
  • NodeJS Path
  • NodeJS Process
  • NodeJS Query String
  • NodeJS Stream
  • NodeJS String Decoder
  • NodeJS Timers
  • NodeJS URL
  • NodeJS Interview Questions
  • NodeJS Questions
  • Web Technology
Open In App
Next Article:
Routing in NodeJS
Next article icon

Signup Form Using Node.js and MongoDB

Last Updated : 08 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Installations

First, we need to include a few packages for our Nodejs application.

npm install express --save

Express allows us to set up middlewares to respond to HTTP Requests.

npm install body-parser --save

If you want to read HTTP POST data , you have to use the “body-parser” node module.

npm install mongoose --save

Mongoose is an object document mapping (ODM) layer which sits on the top of Node’s MongoDB driver.

app.js

This is the main executable application file

app.js




var express=require("express");
var bodyParser=require("body-parser");
  
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/gfg');
var db=mongoose.connection;
db.on('error', console.log.bind(console, "connection error"));
db.once('open', function(callback){
    console.log("connection succeeded");
})
  
var app=express()
  
  
app.use(bodyParser.json());
app.use(express.static('public'));
app.use(bodyParser.urlencoded({
    extended: true
}));
  
app.post('/sign_up', function(req,res){
    var name = req.body.name;
    var email =req.body.email;
    var pass = req.body.password;
    var phone =req.body.phone;
  
    var data = {
        "name": name,
        "email":email,
        "password":pass,
        "phone":phone
    }
db.collection('details').insertOne(data,function(err, collection){
        if (err) throw err;
        console.log("Record inserted Successfully");
              
    });
          
    return res.redirect('signup_success.html');
})
  
  
app.get('/',function(req,res){
res.set({
    'Access-control-Allow-Origin': '*'
    });
return res.redirect('index.html');
}).listen(3000)
  
  
console.log("server listening at port 3000");
 
 

index.html




<!DOCTYPE html>
<html>
<head>
    <title> Signup Form</title>
          
          
<link rel="stylesheet" 
href=
"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" 
integrity=
"sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" 
crossorigin="anonymous">    
          
<link rel="stylesheet" type="text/css" href="style.css">
          
</head>
<body>
      
    <br>
    <br>
    <br>
    <div class="container" >
        <div class="row">
        <div class="col-md-3">
                      
        </div>
                  
        <div class="col-md-6 main">
                      
            <form action="http://localhost:3000/sign_up" method="post">                 
            <h1> Signup form </h1>
                              
            <input class="box" type="text" name="name" id="name" 
            placeholder="Name"  required /><br>
                              
            <input class="box" type="email" name="email" id="email" 
            placeholder="E-Mail " required /><br>
                              
            <input class="box" type="password" name="password" 
            id="password" placeholder="Password " required/><br>
                              
            <input class="box" type="text" name="phone" id="phone"  
            placeholder="Phone Number " required/><br>
                        <br>
            <input type="submit" id="submitDetails"  
            name="submitDetails" value="Submit" /><br>
                      
            </form>
                      
        </div>
                  
                  
        <div class="col-md-3">
        </div>
                  
    </div>
    </div>
</body>
</html>
 
 

signup_success.html




<!DOCTYPE html>
<html>
<head>
    <title> Signup Form</title>
<link rel="stylesheet" 
href=
"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" 
integrity=
"sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" 
crossorigin="anonymous">
          
<link rel="stylesheet" type="text/css" href="style.css">
</head>
    <body>
    <br>
    <br>
    <br>
    <div class="container" >
        <div class="row">
        <div class="col-md-3">
        </div>
                  
        <div class="col-md-6 main">
                      
            <h1> Signup Successful</h1>
                      
        </div>
                  
                  
        <div class="col-md-3">
        </div>
                  
        </div>
    </div>
</body>
</html>
 
 

style.css




.main{
    padding:20px;
    font-family: 'Helvetica', serif;
    box-shadow: 5px 5px 7px 5px #888888;
      
}
.main h1{
    font-size: 40px;
    text-align:center;
    font-family: 'Helvetica', serif;
      
}
input{
    font-family: 'Helvetica', serif;
    width: 100%;
    font-size: 20px;
    padding: 12px 20px;
    margin: 8px 0;
    border: none;
    border-bottom: 2px solid #767474;
}
input[type=submit] {
    font-family: 'Helvetica', serif;
    width: 100%;
    background-color: #767474;
    border: none;
    color: white;
    padding: 16px 32px;
    margin: 4px 2px;
    border-radius: 10px;
}
 
 

Start the MongoDB. Run app.js file

node app.js

Go to the browser and open http://127.0.0.1:3000/

Fill the above form

This will add a record named “David Smith” in MongoDB. Let’s have a check in MongoDB for the same record. The record is now saved in the “gfg” database in “details” collection.



Next Article
Routing in NodeJS

L

latikesh2121
Improve
Article Tags :
  • Node.js

Similar Reads

  • MERN Stack
    The MERN stack is a widely adopted full-stack development framework that simplifies the creation of modern web applications. Using JavaScript for both the frontend and backend enables developers to efficiently build robust, scalable, and dynamic applications. What is MERN Stack?MERN Stack is a JavaS
    9 min read
  • MERN Full Form
    MERN Stack is a JavaScript Stack that is used for easier and faster deployment of full-stack web applications. MERN Stack comprises 4 technologies namely: MongoDB, Express, React, and Node.js. It is designed to make the development process smoother and easier. Table of Content MERN Full Form: What i
    5 min read
  • How to Become a MERN Stack Developer?
    Do you also get amazed at those beautiful websites that appear in front of you? Those are designed by none other than Full-Stack Developers Or MERN stack developers. They are software developers who specialize in building web applications using the MERN stack, which is a popular set of technologies
    6 min read
  • Difference between MEAN Stack and MERN Stack
    Web development is a procedure or process for developing a website. A website basically contains three ends: the client side, the server side, and the database. These three are different sides of an application that combine together to deliver an application; all ends are implemented separately with
    3 min read
  • Best Hosting Platforms for MERN Projects
    Hosting your website grants you the thrilling opportunity to showcase it to the world. Whether you choose free or paid hosting, the process of deploying your website fills you with a mix of excitement, pride, and nervousness. You eagerly await user feedback, enthusiastically embracing the chance to
    5 min read
  • Getting Started with React & Frontend

    • React Introduction
      ReactJS is a component-based JavaScript library used to build dynamic and interactive user interfaces. It simplifies the creation of single-page applications (SPAs) with a focus on performance and maintainability. It is developed and maintained by Facebook.The latest version of React is React 19.Use
      8 min read

    • React Environment Setup
      To run any React application, we need to first setup a ReactJS Development Environment. In this article, we will show you a step-by-step guide to installing and configuring a working React development environment. We will discuss the following approaches to setup environment in React. Table of Conte
      3 min read

    • React Components
      In React, React components are independent, reusable building blocks in a React application that define what gets displayed on the UI. They accept inputs called props and return React elements describing the UI. In this article, we will explore the basics of React components, props, state, and rende
      4 min read

    • ReactJS Props - Set 1
      The react props refer to properties in react that are passed down from parent component to child to render the dynamic content. Till now we have worked with components using static data only. In this article, we will learn about react props and how we can pass information to a Component. What are Pr
      5 min read

    • ReactJS State
      In React, the state refers to an object that holds information about a component's current situation. This information can change over time, typically as a result of user actions or data fetching, and when state changes, React re-renders the component to reflect the updated UI. Whenever state change
      4 min read

    • React Forms
      Forms are an essential part of any application used for collecting user data, processing payments, or handling authentication. React Forms are the components used to collect and manage the user inputs. These components include the input elements like text field, check box, date input, dropdowns etc.
      5 min read

    • React Lists
      React Lists are used to display a collection of similar data items like an array of objects and menu items. It allows us to dynamically render the array elements and display repetitive data. Rendering List in ReactTo render a list in React, we will use the JavaScript array map() function. We will it
      5 min read

    • Create ToDo App using ReactJS
      In this article, we will create a to-do app to understand the basics of ReactJS. We will be working with class based components in this application and use the React-Bootstrap module to style the components. This to-do list can add new tasks we can also delete the tasks by clicking on them. The logi
      3 min read

    Redux Setup and basics

    • Introduction to Redux (Action, Reducers and Store)
      Redux is a state managing library used in JavaScript apps. It simply manages the state of your application or in other words, it is used to manage the data of the application. It is used with a library like React.Uses: It makes easier to manage state and data. As the complexity of our application in
      4 min read

    • Redux and The Flux Architecture
      Flux Architecture: Flux is AN architecture that Facebook uses internally when operating with React. It is not a framework or a library. It is merely a replacement quite an architecture that enhances React and also the idea of unidirectional data flow. Redux is a predictable state container for JavaS
      5 min read

    • React Redux Hooks: useSelector and useDispatch.
      State management is a major aspect of building React applications, allowing users to maintain and update application state predictably. With the introduction of React Hooks, managing state has become even more streamlined and efficient. Among the most commonly used hooks for state management in Reac
      4 min read

    • What are Action's creators in React Redux?
      In React Redux, action creators are functions that create and return action objects. An action object is a plain JavaScript object that describes a change that should be made to the application's state. Action creators help organize and centralize the logic for creating these action objects. Action
      4 min read

    • What is Redux Thunk?
      Redux Thunk is like a co-worker for Redux, giving it the power to handle asynchronous actions. It's that extra tool that allows your Redux store to deal with things like fetching data from a server or performing tasks that take some time. With Redux Thunk, your app can smoothly manage both synchrono
      3 min read

    • Creating custom middlewares in React Redux
      In React-Redux applications, managing the flow of data is crucial for building efficient and scalable apps. Redux provides a powerful state management solution, and custom middleware adds an extra layer of flexibility to handle complex scenarios effectively. Let's understand custom middleware in sim
      5 min read

    • Common middleware libraries used in Redux
      Middleware libraries play a crucial role in Redux applications, enabling users to extend and enhance Redux's capabilities. The middleware libraries offer a wide range of capabilities and cater to different use cases and preferences. users can choose the middleware that best fits their requirements a
      5 min read

    Express and Mongo Setup

    • Mongo with Express Tutorial
      MongoDB and ExpressJS are a powerful pair for web development. MongoDB provides flexible data storage, while ExpressJS simplifies server-side logic. Together, they make it easy to create modern web applications efficiently. MongoDB's document-based approach and ExpressJS's streamlined backend develo
      5 min read

    • How to Install MongoDB on Windows?
      Looking to install MongoDB on your Windows machine? This detailed guide will help you install MongoDB on Windows (Windows Server 2022, 2019, and Windows 11) quickly and efficiently. Whether you’re a developer or a beginner, follow this guide for seamless MongoDB installation, including setting up en
      6 min read

    • How to Install Express in a Node Project?
      ExpressJS is a popular, lightweight web framework for NodeJS that simplifies the process of building web applications and APIs. It provides a robust set of features for creating server-side applications, including routing, middleware support, and easy integration with databases and other services. B
      3 min read

    • Mongoose Module Introduction
      MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term ‘NoSQL’ means ‘non-relational’. MongoDB provides us flexible database schema that has its own advantages and disadvantages. Every record in MongoDB collections does not depend upon the other records pres
      3 min read

    • Mongoose Connections
      A Mongoose connection is a Node.js module that establishes and manages connections between a Node.js application and a MongoDB database. It optimizes resource utilization, handles connection pooling, and manages errors, facilitating efficient data operations. What is Mongoose Connection?A Mongoose c
      6 min read

    • Connect MongoDB with Node App using MongooseJS
      The process of integrating MongoDB, a NoSQL database, with a Node.js application using MongooseJS, a MongoDB object modelling tool designed to work in an asynchronous environment. Prerequisites:NodejsnpmMongoDBMongooseJSSteps to connect MongoDB with Node AppFollowing are the steps to connect MongoDB
      4 min read

    • Node.js CRUD Operations Using Mongoose and MongoDB Atlas
      CRUD (Create, Read, Update, Delete) operations are fundamental in web applications for managing data. Mongoose simplifies interaction with MongoDB, offering a schema-based approach to model data efficiently. MongoDB Atlas is a fully managed cloud database that simplifies the process of setting up, m
      8 min read

    • Signup Form Using Node.js and MongoDB
      Installations First, we need to include a few packages for our Nodejs application. npm install express --save Express allows us to set up middlewares to respond to HTTP Requests. npm install body-parser --save If you want to read HTTP POST data , you have to use the "body-parser" node module. npm in
      3 min read

    API Routing and Authentication

    • Routing in NodeJS
      Routing is the process of deciding how a server should respond to different requests made by users. When you visit a website or use an app, your browser sends a request to the server. Routing determines how the server handles these requests based on the URL you visit and the type of request (such as
      3 min read

    • How to create routes using Express and Postman?
      In this article we are going to implement different HTTP routes using Express JS and Postman. Server side routes are different endpoints of a application that are used to exchange data from client side to server side. Express.js is a framework that works on top of Node.js server to simplify its APIs
      3 min read

    • Difference between application level and router level middleware in Express?
      If you’ve used Express even a little, you know how important middleware is. Those little functions run on every request and let you do stuff like logging, authentication, file uploads, and more. In this article, we will see what is Application-level middleware and Router-level middleware and what ar
      3 min read

    • JWT Authentication In Node.js
      In modern web development, ensuring secure and efficient user authentication is paramount. JSON Web Tokens (JWT) offer a robust solution for token-based authentication, enabling secure transmission of user information between parties. This article provides a step-by-step approach to implementing JWT
      3 min read

    • How To Implement JWT Authentication in Express App?
      Authentication is important in web apps to make sure only the right people can access certain pages or information. It helps keep user data safe and prevents unauthorized access. Implementing JSON Web Token (JWT) authentication in an Express.js application secures routes by ensuring that only authen
      6 min read

    Postman- Backend Testing

    • Introduction to Postman for API Development
      Postman: Postman is an API(application programming interface) development tool that helps to build, test and modify APIs. Almost any functionality that could be needed by any developer is encapsulated in this tool. It is used by over 5 million developers every month to make their API development eas
      7 min read

    • Basics of API Testing Using Postman
      APIs(Application Programming Interfaces) are very commonly used in development. Postman is a tool that can be used for API Testing. In this article, we will learn how to do simple API Testing using Postman. Go to your workspace in Postman.Click on the + symbol to open a new tab.Enter the API Endpoin
      2 min read

    • How to use postman for testing express application
      Testing an Express app is very important to ensure its capability and reliability in different use cases. There are many options available like Thunder client, PAW, etc but we will use Postman here for the testing of the Express application. It provides a great user interface and numerous tools whic
      3 min read

    • How to send different types of requests (GET, POST, PUT, DELETE) in Postman.
      In this article, we are going to learn how can we send different types of requests like GET, POST, PUT, and DELETE in the Postman. Postman is a popular API testing tool that is used to simplify the process of developing and testing APIs (Application Programming Interface). API acts as a bridge betwe
      5 min read

    • How to test GET Method of express with Postman ?
      The GET method is mainly used on the client side to send a request to a specified server to get certain data or resources. By using this GET method we can only access data but can't change it, we are not allowed to edit or completely change the data. It is widely one of the most used methods. In thi
      2 min read

    • How to test POST Method of Express with Postman?
      The POST method is a crucial aspect of web development, allowing clients to send data to the server for processing. In the context of Express, a popular web framework for Node, using the POST method involves setting up routes to handle incoming data. In this article, we'll explore how to test the PO
      2 min read

    • How to test DELETE Method of Express with Postman ?
      The DELETE method is an essential part of RESTful web services used to remove specific resources from a server. Whether you are building a simple API or a complex web application, knowing how to use this method effectively is key. Here, we will explore how to Implement the DELETE method in Express.j
      3 min read

    • How to create and write tests for API requests in Postman?
      Postman is an API(utility programming interface) development device that enables to construct, take a look at and alter APIs. It could make numerous varieties of HTTP requests(GET, POST, PUT, PATCH), store environments for later use, and convert the API to code for various languages(like JavaScript,
      3 min read

geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences