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

Leave a Reply

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