Skip to content

How to fetch data from MongoDB in Node js using Mongoose

  • by
fetch data from MongoDB in Node js using Mongoose

Before guiding you about the procedure to fetching data from MongoDB in node js using mongoose, we will define all three softwares, for the beginners of this field.

Let’s begin!

Contents

MongoDB

MongoDB is an open-source, document-based NoSQL database system. NoSQL is databases that differ from the classic model. The traditional SQL term “NoSQL” was first used in 1998 when it was coined by Carlo Strozzi.

Their advantages over normal MySQL are their more horizontal measurement, no interruptions, no handling of large amounts of data, no need for expensive clusters, etc.

MongoDB comes from the English “Humgons” which is written in C ++ and is released under the license of Apache. On the project’s website, you can find binary for different operating systems, Linux, FreeBSD, Windows, OSX, and Solaris.

Since its release in 2009, its development has reached stable version 2.4.4, although development version 2.5.0 is ready already.

NODE JS?

Node.js is an open-source cross-platform runtime environment used for server-side and networking, specifically for the development of server-side applications. Node.js uses JavaScript as the scripting language.

It initially includes a library of HTTP servers so that the webserver can be run without the use of any external software. This gives them more control over the web server’s operations.

MONGOOSE?

Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node. js, It manages the relationship between the data, provides schema validation, and is used to translate between the objects in the code and the representation of those objects in MongoDB.

MongoDB is a schemaless NoSQL document database.

Fetch Data From MongoDB in node JS using MonGoose

Before getting started, you must configure the following basic steps:

Install Node.js on your device install MongoDB Community ServerAlso, Install MongoDB Compass and create a Database with the name node app & Collection with the name users insert Data into MongoDB Table.

Install Express Application

First of all, you have to Install Express Application. After that, create the following folders & files

nodeapp/ |__controllers/ | |__fetch-controller.js |__models/ | |__fetch-model.js |__routes/ | |__fetch-route.js |__views/ | |__user-table.ejs |__database.js

Connect Node.js to MongoDB database

Now, you have to connect Node.js to the MongoDB database using the following script

File Name – database.js

var mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/nodeapp', {useNewUrlParser: true}

var conn = mongoose.connection;

conn.on('connected' function)

console.log('database is connected successfully)

conn.on('disconnected'function

console.log('database is disconnected successfully)

conn.on('error', console.error.bind(console, 'connection error)

module.exports = conn;

Create a Model to Fetch Data

Create a model to fetch data using the following points:

Include mongoose module using require(‘mongoose’)Also, Include a MongoDb database connection file using require(database)Create a schema with collection columns like full_name, email_address, city & country.Pass MongoDB table users & user Schema to the mongoose.model( )Write a mongoose query within module.exports to fetch data from the MongoDB database

File Name – fetch-model.js

var mongoose=require(mongoose)

var db = require(database)

// create a schema

var userSchema = new mongoose.Schema

full_name: String,

email_address:String,

city:String,

country:String

userTable=mongoose.model('users',userSchema);

module.exports

fetchData:function(callback)

var userData=userTable.find(

userData.exec(function(err, data)

if(err) throw err;

return callback(data)

Create a Controller to Fetch Data

Create a controller to fetch data using the following points:

Include a model file using require(‘../models/fetch-model’)Create a method fetchData within module.exports{}Write mongoose query within fetchData to fetch data from the MongoDB table and pass to the view with userData.

File Name – fetch-controller.js

var fetchModel= require(models/fetch-model)

module.exports= fetchData:function(req, res)

fetchModel.fetchData(function(data){

res.render('user-table',{userData:data}

Display Data in HTML Table

Display data in an HTML table with the help of fetchData that comes from the controller.

File Name – user-table.ejs

<!DOCTYPE html>

<html lang="en">

<head>

<title></title>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1">

<style type="text/css">

table, td, th {

border: 1px solid #ddd;

text-align: left;

table

border-collapse: collapse;

width: 50%

.table-data{

position: relative;

left:50px;

top:50px;

th, td

padding: 15px;

</style>

</head>

<body>

<!--====form section start====-->

<div class="table-data">

<table border="1" >

<tr>

<th>S.N</th>

<th>Full Name</th>

<th>Email Address</th>

<th>City</th>

<th>Country</th>

<th>Edit</th>

<th>Delete</th>

</tr>

<%

if(userData.length!=0){

var i=1;

userData.forEach(function(data)

%>

<tr>

<td><%=i; %></td>

<td><%=data.full_name %></td>

<td><%=data.email_adress %></td>

<td><%=data.city %></td>

<td><%=data.country %></td>

<td><a href="/edit/<%=data.id%>">Edit</a></td>

<td><a href="/delete/<%=data.id%>">Delete</a></td>

</tr>

<% i++; }) %>

<% } else{ %>

<tr>

<td colspan="7">No Data Found</td>

</tr>

<% } %>

</table>

</div>

</body>

</html>

Create a Route to fetch Data

Create a route to fetch data with the help of the following points

Include a controller file using require(‘../controllers/fetch-controller’)Create a route /fetch-data with GET method to fetch data from the MongoDB database.

File Name – fetch-route

var express = require(express)

var router = express.Router();

var fetchController= require(controllers/fetch-controller)

router.get('/fetch-data',fetchController.fetchData);

module.exports = router;

Include and Use the Router in app.js

Now, You have to include & use the fetched route in the main root file app.js

File Name – app.js

var fetchRouter = require('./routes/fetch-route');

app.use('/', fetchRouter);

Run Node.js app to Fetch Data

First, start the Node.js server. after that, Enter the following URL in your browser to display data in the HTML table.

http://localhost:3000/fetch-data

Hope this guide is helpful for you. You should have a quick guide on: How to Install Tensorflow on Mac.

Leave a Reply

Your email address will not be published. Required fields are marked *