Steps on How to get data from MongoDB using NodeJS

Step 1: Create a New Directory: At first create a new directory for your project and navigate into it.

mkdir Your_folder_name

cd Your_folder_name

Step 2: Initialize a New Node.js Project: After that, you have to Initialize a new node project using npm.

npm init -y

Step 3: Install required packages: Then install the required package using npm.

npm install express mongoose ejs

Step 4: Require Mongoose: After that in your NodeJS application, you need to require Mongoose.

const mongoose = require('mongoose');

Step 5: Call the connect method: Then you need to call the Mongoose connect method to connect it.

const mongoose = require('mongoose');

const url = 'mongodb://localhost:27017/userData';

const connectDB = async () => {
try {
await mongoose.connect(url, {

});
console.log('Database is connected');
} catch (err) {
console.error('Error connecting to the database:', err);
process.exit(1);
}
};

Step 6: Then Define a schema: A schema is a structure, that gives information about how the data is being stored in a collection.

const userSchema = new Schema({
name: {
type: String,
required: true,
},
email:{
type:String,
required:true,
},
mobile:{
type: Number,
required: true,
},
age: {
type: Number,
required: true,
},
});

//Here you can add some more data as your need.

Project Structure:

Folder structur

Updated dependencies:

 "dependencies": {
"ejs": "^3.1.10",
"express": "^4.19.2",
"mongoose": "^8.3.4"
}


Example: Below is the code example of how to get data from MongoDB using node js

HTML
<!-- view/index.ejs !-->

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Home Page</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f9f9f9;
            margin: 0;
            padding: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
        }

        .container {
            max-width: 400px;
            padding: 20px;
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }

        h1 {
            color: #333;
            text-align: center;
            margin-bottom: 20px;
        }

        p {
            color: #666;
            text-align: center;
            margin-bottom: 20px;
        }

        form {
            text-align: center;
        }

        label {
            display: block;
            margin-bottom: 10px;
            color: #333;
        }

        input[type="text"],
        input[type="email"],
        input[type="tel"],
        input[type="number"],
        button {
            width: 100%;
            padding: 10px;
            margin-bottom: 15px;
            border: 1px solid #ccc;
            border-radius: 5px;
            box-sizing: border-box;
        }

        button {
            background-color: #007bff;
            color: #fff;
            cursor: pointer;
        }

        button:hover {
            background-color: #0056b3;
        }

        .message {
            color: green;
            text-align: center;
            margin-bottom: 20px;
        }

        .error {
            color: red;
            text-align: center;
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Welcome to our website!</h1>
        <p>This is a simple form to save user data to the database.</p>
        <form id="userForm" action="/user" method="post" onsubmit="return validateForm()">
            <label for="name">Name:</label>
            <input type="text" id="name" name="name" >
            <label for="email">Email Id:</label>
            <input type="email" id="email" name="email" >
            <label for="mobile">Mobile No:</label>
            <input type="tel" id="mobile" name="mobile" pattern="[0-9]{10}">
            <label for="age">Age:</label>
            <input type="number" id="age" name="age" >
            <button type="submit">Submit</button>
        </form>
        <% if (message) { %>
            <p class="message"><%= message %></p>
        <% } else if (error) { %>
            <p class="error"><%= error %></p>
        <% } %>
    </div>

    <script>
        function validateForm() {
            var name = document.getElementById("name").value;
            var email = document.getElementById("email").value;
            var mobile = document.getElementById("mobile").value;
            var age = document.getElementById("age").value;

            if (name === "" || email === "" || mobile === "" || age === "") {
                alert("Please fill out all fields.");
                return false;
            }

            if (!/^[0-9]{10}$/.test(mobile)) {
                alert("Please enter a valid 10-digit mobile number.");
                return false;
            }

            return true;
        }
    </script>
</body>
</html>
HTML
<!-- view/userdata.ejs !-->

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>User Data</title>
    <style>
        body {
            font-family: 'Arial', sans-serif;
            background-color: #f0f2f5;
            margin: 0;
            padding: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
        }

        .container {
            max-width: 800px;
            width: 100%;
            margin: 20px;
            padding: 20px;
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }

        h1 {
            color: #333;
            text-align: center;
            margin-bottom: 20px;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
            overflow-x: auto;
        }

        th, td {
            padding: 12px;
            border: 1px solid #ddd;
            text-align: left;
            white-space: nowrap;
        }

        th {
            background-color: #007bff;
            color: #fff;
        }

        tr:nth-child(even) {
            background-color: #f9f9f9;
        }

        .error {
            color: red;
            text-align: center;
            margin-bottom: 20px;
        }

        .btn-back {
            display: inline-block;
            margin-top: 20px;
            padding: 10px 20px;
            background-color: #007bff;
            color: #fff;
            text-decoration: none;
            border-radius: 5px;
            text-align: center;
            transition: background-color 0.3s;
        }

        .btn-back:hover {
            background-color: #0056b3;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>User Data</h1>
        <% if (error) { %>
            <p class="error"><%= error %></p>
        <% } %>
        <table>
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Email</th>
                    <th>Mobile</th>
                    <th>Age</th>
                </tr>
            </thead>
            <tbody>
                <% users.forEach(user => { %>
                    <tr>
                        <td><%= user.name %></td>
                        <td><%= user.email %></td>
                        <td><%= user.mobile %></td>
                        <td><%= user.age %></td>
                    </tr>
                <% }) %>
            </tbody>
        </table>
        <a href="/" class="btn-back">Back to Home</a>
    </div>
</body>
</html>
JavaScript
//server.js

const express = require('express');
const connectDB = require('./database/db');
const userRoutes = require('./routes/userRoutes');

const app = express();
const port = 3000;

// Connect to the database
connectDB();

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

// Set the view engine to EJS
app.set('view engine', 'ejs');
app.set('views', './views');

// Routes
app.use('/', userRoutes);

// Start the server
app.listen(port, (err) => {
  if (err) {
    console.log(err);
  } else {
    console.log(`Server is started at port ${port}`);
  }
});
JavaScript
// databse/db.js

const mongoose = require('mongoose');
const url = 'mongodb://localhost:27017/userData';
const connectDB = async () => {
    try {
        await mongoose.connect(url, {
           
        });
        console.log('Database is connected');
    } catch (err) {
        console.error('Error connecting to the database:', err);
        process.exit(1);
    }
};

module.exports = connectDB;
JavaScript
//model/model.js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const userSchema = new Schema({
  name: {
    type: String,
    required: true,
  },
  email:{
    type:String,
    required:true,
  },
  mobile:{
    type: Number,
    required: true,
  },
  age: {
    type: Number,
    required: true,
  },
});

const User = mongoose.model('User', userSchema);

module.exports = User;
JavaScript
// routes/userRoutes.js

// routes/userRoutes.js

const express = require('express');
const User = require('../model/model');
const router = express.Router();

// GET route for the home page
router.get('/', async (req, res) => {
  try {
    const users = await User.find();
    res.render('index', { message: null, error: null, users });
  } catch (err) {
    console.error('Error fetching user data:', err);
    res.status(500).render('index', { error: 'Error fetching user data', users: [] });
  }
});

// POST route for adding a user
router.post('/user', async (req, res) => {
  try {
    const newUser = new User({
      name: req.body.name,
      email: req.body.email,
      mobile: req.body.mobile,
      age: req.body.age,
    });
    await newUser.save();
    res.render('index', { message: 'User data saved successfully!', error: null, users: await User.find() });
  } catch (err) {
    console.error('Error saving user data:', err);
    res.status(500).render('index', { error: 'Error saving user data', message: null, users: [] });
  }
});

// GET route for displaying user data in a separate view
router.get('/userdata', async (req, res) => {
  try {
    const users = await User.find();
    res.render('userdata', { users, error: null });  
  } catch (err) {
    console.error('Error fetching user data:', err);
    res.status(500).render('userdata', { error: 'Error fetching user data', users: [] });
  }
});

module.exports = router;


Output:



How to Get Data from MongoDB using Node.js?

One can create a simple Node.js application that allows us to get data to a MongoDB database. Here we will use Express.js for the server framework and Mongoose for interacting with MongoDB. Also, we use the EJS for our front end to render the simple HTML form and a table to show the data.

Prerequisites:

Similar Reads

Steps on How to get data from MongoDB using NodeJS

Step 1: Create a New Directory: At first create a new directory for your project and navigate into it....