Fetch Data from Mongodb using Mongoose, Express.js, Node.js

Fetch Data from Mongodb using Mongoose, Express.js, Node.js

In this post we have learn how to fetch data from mongodb using mongoose, express.js and node.js. Also we solve all about the related questions like get data from mongodb node js using mongoose, fetch data from mongodb using mongoose, getting data from mongodb using mongoose, get data from mongoose node js, how to get data from mongodb using mongoose, read data from mongodb using mongoose, how to retrieve data from mongodb using mongoose.

How to Fetch Data from Mongodb using Mongoose,Express.js,Node.js

Step 1 : Install MongoDB

First you can install mongoDB environment  on your system. Install mongoDB from official website https://www.mongodb.com.

step 2: Install required packages

Following package to you can easy to mongoose insert document in your project.

  • Express – popular web framework;
  • body-parser – body parser middleware, allows to access req.body property;
  • mongoose – Mongoose provides a straight-forward;
Read Also :  Update Data in MongoDB using Node js

Following command to install express module in node js, install bosy-parser .

npm init -y
npm i express body-parser mongodb

Example : Getting data from mongoDB using mongoose

Step 1 : Create the db.js file on your root directory in this file we will import mongoose module and connect with mongoDB database. In this file you include your model.

db.js

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/testdb', { useNewUrlParser: true }, (err) => {
    if (!err) {
        console.log('MongoDB Connection Succeeded.')
    }else {
        console.log('Error in DB connection : ' + err)
    }
});

require('./models/users');

Step 2 :  Create views/layout/layout.hbs file. If you have use handlebars(.hbs) extension, hbs require views folder.

views/layout/layout.hbs

<!DOCTYPE html>
<html>
<head>
    <title>how to retrieve data from mongodb using mongoose</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"
        crossorigin="anonymous">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body class="bg-info">
    <div class="row">
        <div class="col-md-6 offset-md-3" style="background-color: #fff;margin-top: 25px;padding:20px;">
            {{{body}}}
        </div>
    </div>
</body>
</html>

Step 3 : Create the views/user/list.hbs file. In this file we have create basic html form for get data from mongoose nodejs. In this form we have display user data using mongoose and nodejs.

Read Also :  Crud Operation using Node.js Express MongoDB

views/user/list.hbs

<h3><a class="btn btn-secondary" href="/"><i class="fa fa-plus"></i> Create New</a> User List</h3>
<table class="table table-striped">

    <thead>
        <tr>
            <th>Username</th>
            <th>Email</th>
            <th>Passwod</th>
            <th></th>
        </tr>
    </thead>

    <tbody>
        {{#each list}}
        <tr>
            <td>{{this.username}}</td>
            <td>{{this.email}}</td>
            <td>{{this.password}}</td>
            <td>
                <a href="/{{this._id}}"><i class="fa fa-pencil fa-lg" aria-hidden="true"></i></a>
                <a href="/delete/{{this._id}}" onclick="return confirm('Are you sure to delete this record ?');"><i class="fa fa-trash fa-lg" aria-hidden="true"></i></a>
            </td>
        </tr>
        {{/each}}
    </tbody>
</table>

Step 4 : Create the server.js file in root directory. This file is by default run your project. In this file we have include db.js connection file.

server.js

require("./db");
const path = require("path");
const express = require("express");
const bodyparser = require("body-parser");
const exphbs = require("express-handlebars");
const userController = require("./controllers/userController");

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

app.use(bodyparser.json());
app.set('views', path.join(__dirname, '/views/'));
app.engine('hbs', exphbs({ extname: 'hbs', defaultLayout: 'layout',
        runtimeOptions: {
          allowProtoPropertiesByDefault: true,
          allowProtoMethodsByDefault: true,
        },
     layoutsDir: __dirname + '/views/layout' }));

app.set('view engine', 'hbs');
app.listen(3000, () => {
    console.log('Express server started at port : 3000');
});

app.use('/', userController);

Step 5 : Create controllers/userController.js file. In file we have create router and write some code like getting data from mongodb using mongoose, get data from mongoose node js, how to get data from mongodb using mongoose.

Read Also :  How do I read a JSON file in node JS

controllers/userController.js

const express = require("express");
var router = express.Router();
const mongoose = require('mongoose');
const Users = mongoose.model('Users');
mongoose.set('useFindAndModify', false);
       
router.get('/list', (req, res) => {

    Users.find((err, docs) => {
        if (!err) {
            res.render("user/list", {
                list: docs
            });
        }
        else {
            console.log('Error in retrieving users list :' + err);
        }
    });
});

module.exports = router;

Step 6 : Complete all steps after you can enter the following command.

npm server.js