Fetch Individual User Data From MongoDB: Node.js

In most modern-day applications we’ll need to show particular user information on their respective profile page. In today’s video tutorial, we’ll show you just that.

my-profile-page

We’ve already learnt how to connect to MongoDB server, insert/save data and retrieve all the inserted data out of the database.
Related Read:
Connecting To MongoDB Using Mongoose: Node.js
Save data To MongoDB: Node.js
Fetch Data From MongoDB: Node.js
..please go through all these 3 tutorials before proceeding further. It’ll take less than 20 min

This is all very important – with that, retrieving single user information upon request is most common thing in modern-day web applications. So lets learn that today.

Retrieving Individual user information
app.js

1
2
3
4
5
6
app.get('/user/:id', function(req, res){
user.find({_id: req.params.id}, function(err, docs){
if(err) res.json(err);
else    res.render('show', {user: docs[0]});
});
});

Here we’re creating a route for /user/:id We pass id of the user as first parameter to find() method. Once it retrieves that particular users information, we assign the first object in the result to user object and pass it on to show.jade template file.

Note: find() returns array of objects as result. But in fact, since we’re retrieving single user information in above case, we always get single object inside the result array. Thus, we assign docs[0] to user object.

Shift the logic to param
app.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
app.param('id', function(req, res, next, id){
user.findById(id, function(err, docs){
if(err) res.json(err);
else
{
req.userId = docs;
next();
}
});
});
 
app.get('/user/:id', function(req, res){
res.render('show', {user: req.userId});
});

In param we must match the param name – in above example snippet, name is id Also we’re using findById() method which is a method by mongoose module. It’s comparatively faster than find() method. findById() returns a single object, hence we can directly use it.

Here we fetch the particular user information and if successful, we copy the result object into req.userId variable, and call next(), which passes the control to next level, where it renders the result on show.jade template file.

Fetch Individual User Data From MongoDB: Node.js


[youtube https://www.youtube.com/watch?v=rQ4LvkZOa94]

YouTube Link: https://www.youtube.com/watch?v=rQ4LvkZOa94 [Watch the Video In Full Screen.]



Full code
app.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
var express = require('express');
var http = require('http');
var path = require('path');
var mongoose = require('mongoose');
 
var app = express();
 
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
 
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
 
mongoose.connect('mongodb://localhost/Company');
 
var Schema = new mongoose.Schema({
_id    : String,
name: String,
age   : Number
});
 
var user = mongoose.model('emp', Schema);
 
app.param('id', function(req, res, next, id){
user.findById(id, function(err, docs){
if(err) res.json(err);
else
{
req.userId = docs;
next();
}
});
});
 
app.get('/user/:id', function(req, res){
res.render('show', {user: req.userId});
});
 
app.get('/view', function(req, res){
user.find({}, function(err, docs){
if(err) res.json(err);
else    res.render('index', {users: docs})
});
});
 
app.post('/new', function(req, res){
new user({
_id    : req.body.email,
name: req.body.name,
age   : req.body.age
}).save(function(err, doc){
if(err) res.json(err);
else    res.redirect('/view');
});
});
 
var server = http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

Note: Make sure to have a form at index.html and place it inside public folder. Also make sure to have email, name and age input fields.

Above code has these functionality coded in it:
Insert Data : /new
Fetch Date : /view
Fetch Individual Data : /user/:id

Fetch/Extract Data From Database Without Refreshing Webpage: jQuery

Video tutorial illustrating, Fetching / Extraction of Data From Database Without Refreshing Webpage: jQuery + PHP + JSON + MySQL

You need not worry, even if you don’t know any one of these technology. Follow the tutorial, practice and understand, so that you could implement it for your applications.

Also read: Insert Data Into Database Without Refreshing Webpage.

In this tutorial we’ll be showing you, how to extract the data present in our MySQL database table without refreshing the webpage.

HTML code
index.html

1
2
3
4
5
6
7
8
9
10
<html>
<head>
<title>Fetch/Extract Data From Database: jQuery + JSON + PHP+ AJAX</title>
</head>
<body>
<ul></ul>
<script type="text/javascript" src="script/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="script/my_script.js"></script>
</body>
</html>

Here we have a unordered list. We’ll fill it’s list items by extracting the data from the database, using jQuery and PHP.

PHP File: Database Connection Code
db.php

1
2
3
4
< ?php
      $conn = mysql_connect('localhost', 'root', '');
  $db   = mysql_select_db('company');
?>

Here we’re connecting to the database called company.

Also Read: Connecting To MySQL server From PHP

PHP File: Extracting / Fetching Data From Database table and JSON Encoding
fetch.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
< ?php
        include_once('db.php');
 
$sql = "SELECT * FROM people";
$res = mysql_query($sql);
$result = array();
 
while( $row = mysql_fetch_array($res) )
    array_push($result, array('name' => $row[0],
                          'age'  => $row[1],
  'company' => $row[2]));
 
echo json_encode(array("result" => $result));
?>

Here we connect to the database by including db.php file.
Next, select all the fields from the people table.
Extract data one-by-one and store it inside the array variable $result, with key => value pair (associative array).
Finally, using PHP standard function json_encode(), we encode the fetched data.

jQuery File: Accessing The Data And Displaying
my_script.js

1
2
3
4
5
6
7
8
9
10
11
function updates() {
 $.getJSON("fetch.php", function(data) {
       $("ul").empty();
   $.each(data.result, function(){
    $("ul").append("<li>Name: "+this['name']+"</li>
                            <li>Age: "+this['age']+"</li>
                            <li>Company: "+this['company']+"</li>
                            <br />");
   });
 });
}

Using the jQuery AJAX method’s shortcut, $.getJSON() method, we parse fetch.php and process the data passed to the callback function.

We empty the unordered list to avoid duplicate entries later on.

Now loop through all the objects present in the jSON output of fetch.php
Using it’s key, retrieve it’s respective values and append it to the unordered list, as it’s list items.

jQuery File: AJAXing
my_script.js

1
2
3
4
5
6
function done() {
  setTimeout( function() { 
  updates(); 
  done();
  }, 200);
}

Call updates() function and itself[ done() ] inside setTimeout() function with a time gap of 200 milliseconds.

jQuery File: Full/Final Code
my_script.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
$(document).ready( function() {
 done();
});
 
function done() {
  setTimeout( function() { 
  updates(); 
  done();
  }, 200);
}
 
function updates() {
 $.getJSON("fetch.php", function(data) {
       $("ul").empty();
   $.each(data.result, function(){
    $("ul").append("<li>Name: "+this['name']+"</li>
                            <li>Age: "+this['age']+"</li>
                            <li>Company: "+this['company']+"</li>
                            <br />");
   });
 });
}

Call done() once the document is loaded.
You could also call done() function once the window is focused or once some button is clicked or any other user events. This would reduce the database calls considerably.

Fetching / Extraction of Data From Database Without Refreshing Webpage: jQuery


[youtube https://www.youtube.com/watch?v=G_7oYeNU_3g]

YouTube Link: https://www.youtube.com/watch?v=G_7oYeNU_3g [Watch the Video In Full Screen.]



This would highly enhance the user experience and would help in building rich web applications which look more like desktop / standalone applications.

Please share this video with your friends and also LIKE it on social network sites and on YouTube. Thanks you <3

Related Read:
Insert Data Into Database Without Refreshing Webpage

SELECT / LIST Records From Database Table: PHP & MySQL

Video tutorial demonstrates selecting / listing / fetching of data / records from the database table and displaying it on the browser.

First look at these short videos:
Connect to the database
Simple / basic insertion operation
Insertion of Records into Database using Forms: PHP & MySQL (important)

SELECTING and Displaying Data
index.php

1
2
3
4
5
6
7
8
9
< ?php
  include_once('db.php');
 
 $res = mysql_query("SELECT * FROM apple");
 
  while( $row = mysql_fetch_array($res) )
  echo "$row[id]. $row[name] <br />";
 
?>

Video Tutorial: SELECT / LIST Records From Database Table: PHP & MySQL


[youtube https://www.youtube.com/watch?v=OAT0iTXlqCk]

YouTube Link: https://www.youtube.com/watch?v=OAT0iTXlqCk [Watch the Video In Full Screen.]



Full code
index.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
< ?php
include_once('db.php');
 
if(isset($_POST['name']))
{
  $name = $_POST['name'];
 
  if(mysql_query("INSERT INTO apple VALUES('','$name')"))
echo "Successful Insertion!";
  else
echo "Please try again";
}
 
 
$res = mysql_query("SELECT * FROM apple");
 
 
?>
 
<form action="." method="POST">
Name: <input type="text" name="name"/><br />
<input type="submit" value=" Enter "/>
</form>
 
<h1>List of companies ..</h1>
< ?php
while( $row = mysql_fetch_array($res) )
  echo "$row[id]. $row[name] <br />";
?>

while loop executes until there is data inside the table, once there is no more data to fetch, loop terminates.

MySQL Query

1
mysql> SELECT * FROM apple;

This mysql statement fetches data from all the fields of the table.
We could specify fields and get only list of those values.

Ex:

1
mysql> SELECT id FROM apple;

Using this we can get list of id’s only.

After fetching data from table apple

List of companies ..

1. Google
2. Apple
3. Microsoft
4. Oracle
5. Technotip