Equal to v/s Strictly Equal to

What’s the difference between equal to v/s strictly equal to and not equal to v/s strictly not equal to in any programming language?

This seems to be confusing at first, but if we execute a small example things get very clear about the working of these operators.

strictly-not-equal-to

== is called equal to operator.
!= is called not-equal to operator.
=== is called strictly equal to operator.
!== is called strictly not-equal to operator.

In this video tutorial we shall see the differences between == v/s === and != v/s !===

Difference between != v/s !=== and == v/s ===


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

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



$a = 1;
$b = '1';

Lets assign integer 1 to variable a and string ‘1’ to variable b.

Equal-to v/s Strictly Equal-to

$a == $b
true
 
$a === $b
false

== operator doesn’t consider the type of variable strictly, thus returns true even though we are comparing a string with an integer. But === operator considers the type of the variable strictly and treats integer and string as two different things and hence returns false.

Not Equal-to v/s Strictly Not Equal-to

$a != $b
false
 
$a !== $b
true

Similarly, as != operator doesn’t take variable type into strict consideration it thinks $a and $b as equals, hence returns false, but !== returns true as it reads integer and string variables as different.

Remove / Delete Data From MongoDB: Node.js

Today lets learn how to delete documents from MongoDB collection via your node.js application.

remove-delete-data-mongoDB-nodejs

In this video tutorial, I’ll show you how to make use of normal app.get to delete data and also the use of app.delete to accomplish the same.

Related Read:
Connecting To MongoDB Using Mongoose: Node.js
Save data To MongoDB: Node.js
Fetch Data From MongoDB: Node.js
Fetch Individual User Data From MongoDB: Node.js
Update / Edit Data In MongoDB: Node.js
..please go through these tutorials before proceeding further. It’ll take less than 20 min

Adding Delete link
view/show.jade

1
2
3
4
5
6
7
8
<h1>#{user.name}</h1>
ul
 li Age: #{user.age}
 li Email: #{user._id}
 
ul
 li 
  a(href="/user/#{user._id}/delete") Delete

This adds Delete link below each individual user information.

Delete Routes: remove()
app.js

1
2
3
4
5
6
7
8
9
var user = mongoose.model('emp', Schema);
 
app.get('/user/:id/delete', function(req, res){
user.remove({_id: req.params.id}, 
   function(err){
if(err) res.json(err);
else    res.redirect('/view');
});
});

Here we simply make use of app.get and the route we are defining is /user/:id/delete Once the user clicks on the delete link with the user id in it, the route gets triggered and by using remove() method upon user object, we fetch the user data with the particular id that the user passed in from the URL and delete it from our mongoDB collection.

Delete Routes: findByIdAndRemove()
app.js

1
2
3
4
5
6
7
8
9
var user = mongoose.model('emp', Schema);
 
app.get('/user/:id/delete', function(req, res){
user.findByIdAndRemove({_id: req.params.id}, 
   function(err, docs){
if(err) res.json(err);
else    res.redirect('/view');
});
});

Here we are using findByIdAndRemove() method of mongoose module to find the requested user and delete the user document. Syntax is same as remove() method, only change is, findByIdAndRemove() method also returns result object to the callback method along with error object.

app.delete
view/show.jade

1
2
3
4
5
6
7
8
9
10
11
12
<h1>#{user.name}</h1>
ul
 li Age: #{user.age}
 li Email: #{user._id}
 
ul
 li 
  a(href="/user/#{user._id}/edit") Edit
 li
  form(action="/user/#{user._id}", method="POST")
   input(type="hidden", name="_method", value="DELETE")
   button(type="submit") Delete

Here we replace the delete link with a delete button. Here the action field value is /user/#{user._id} and the method used is POST. But we are also passing a hidden input field which overrides the method from POST to DELETE inside our node application.

Delete Routes: app.delete() and findByIdAndRemove()
app.js

1
2
3
4
5
6
7
8
9
var user = mongoose.model('emp', Schema);
 
app.delete('/user/:id', function(req, res){
user.findByIdAndRemove({_id: req.params.id}, 
   function(err, docs){
if(err) res.json(err);
else    res.redirect('/view');
});
});

The findByIdAndRemove() method works the same way as explained above.

Delete Routes: app.delete() and remove()
app.js

1
2
3
4
5
6
7
8
9
var user = mongoose.model('emp', Schema);
 
app.delete('/user/:id', function(req, res){
user.remove({_id: req.params.id}, 
   function(err){
if(err) res.json(err);
else    res.redirect('/view');
});
});

The remove() method works the same way as explained above.

Remove / Delete Data From MongoDB: Node.js


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

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



Full Source Code

new user registration form
public/index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
< !DOCTYPE html>
<html>
<head>
<title>Registration Form</title>
</head>
<body>
 <form action="/new" method="POST">
<label for="email">Email: </label>
  <input type="email" name="email" /><br />
<label for="name">Name: </label>
  <input type="text" name="name" /><br />
<label for="age">Age: </label>
  <input type="number" name="age" /><br />
 <input type="submit"/>
</form>
</body>
</html>

Link to all registered users
view/index.jade

1
2
3
4
ul
each user in users
 li
  a(href='/user/#{user._id}') #{user.name}

Edit form
view/edit-form.jade

1
2
3
4
5
6
7
8
9
<h1>Editing #{user.name}'s profile!</h1>
form(method="POST", action="/user/#{user._id}")
 input(type="hidden", name="_method", value="PUT")
 p Name:
  input(type="text", name="name", value="#{user.name}")
 p Age:
  input(type="number", name="age", value="#{user.age}")
 p
  input(type="submit")

Show Individual User Information
view/show.jade

1
2
3
4
5
6
7
8
9
10
11
12
<h1>#{user.name}</h1>
ul
 li Age: #{user.age}
 li Email: #{user._id}
 
ul
 li 
  a(href="/user/#{user._id}/edit") Edit
 li
  form(action="/user/#{user._id}", method="POST")
   input(type="hidden", name="_method", value="DELETE")
   button(type="submit") Delete

Main Node.js Application File, with Create, Read, Update and Delete Routes
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
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.delete('/user/:id', function(req, res){
user.findByIdAndRemove({_id: req.params.id}, 
   function(err, docs){
if(err) res.json(err);
else    res.redirect('/view');
});
});
 
app.get('/user/:id/edit', function(req, res){
res.render('edit-form', {user: req.userId});
});
 
app.put('/user/:id', function(req, res){
user.findByIdAndUpdate({_id: req.params.id},
                   {
     name: req.body.name,
  age   : req.body.age
   }, function(err, docs){
 if(err) res.json(err);
else
{ 
   console.log(docs);
   res.redirect('/user/'+req.params.id);
 }
 });
});
 
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'));
});

Routes
/ for new entries
/view for viewing all the users
/user/:id to see individual user information
/user/:id/edit to edit individual user information

With these tutorials you can start building fully functional web application. But to make it more secure, incorporate sessions, validation and error handling.

Update / Edit Data In MongoDB: Node.js

Today lets look at editing and updating user entered data via Node.js application.

edit-update-data-mongoDB-nodejs

Related Read:
Connecting To MongoDB Using Mongoose: Node.js
Save data To MongoDB: Node.js
Fetch Data From MongoDB: Node.js
Fetch Individual User Data From MongoDB: Node.js
..please go through these 4 tutorials before proceeding further. It’ll take less than 20 min

link to individual profile page
view/index.jade

1
2
3
4
ul
each user in users
 li
  a(href='/user/#{user._id}') #{user.name}

This displays list of all the users with their name, hyper-linked with their email id(present inside _id).

Adding Edit link
view/show.jade

1
2
3
4
5
6
7
8
<h1>#{user.name}</h1>
ul
 li Age: #{user.age}
 li Email: #{user._id}
 
ul
 li 
  a(href="/user/#{user._id}/edit") Edit

This adds Edit link below each individual user information.

Edit Form
view/edit-form.jade

1
2
3
4
5
6
7
8
9
<h1>Editing #{user.name}'s profile!</h1>
form(method="POST", action="/user/#{user._id}")
 input(type="hidden", name="_method", value="PUT")
 p Name:
  input(type="text", name="name", value="#{user.name}")
 p Age:
  input(type="number", name="age", value="#{user.age}")
 p
  input(type="submit")

It shows a message letting know the user, which user’s information they are editing. Also it fills the previous values for name and age. You can find a hidden field with the name _method, which helps to override POST method, and facilitates PUT method.

Edit and Update Routes
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
app.get('/user/:id/edit', function(req, res){
res.render('edit-form', {user: req.userId});
});
 
app.put('/user/:id', function(req, res){
user.update({_id: req.params.id},
                   {
     name: req.body.name,
  age   : req.body.age
   }, function(err, docs){
 if(err) res.json(err);
else    res.redirect('/user/'+req.params.id);
 });
});
 
app.param('id', function(req, res, next, id){
user.findById(id, function(err, docs){
if(err) res.json(err);
else
{
req.userId = docs;
next();
}
});
});

Here id matches the param call, and using findById() method of mongoose, it fetches all the users present in the database. Once we call next(), it passes the control to next level. At /user/:id/edit route, we render edit-form.jade file and pass it with user information, to be filled inside the form input fields.

Once the user makes changes to the values and submits the form, all the values are passed to /user/:id route. In /user/:id route, we call update() method and specify which user information has to be updated in its first parameter, in second parameter we specify all the fields to be updated, and the third parameter is a callback method and it only takes error object as argument.

Using findByIdAndUpdate() method
app.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
app.put('/user/:id', function(req, res){
user.findByIdAndUpdate({_id: req.params.id},
                   {
     name: req.body.name,
  age   : req.body.age
   }, function(err, docs){
 if(err) res.json(err);
else
{ 
   console.log(docs);
   res.redirect('/user/'+req.params.id);
 }
 });
});

Syntax of findByIdAndUpdate() method is same as that of update(), only difference is, findByIdAndUpdate() returns the result object as well as error object to the callback method. We can make use of result object to our advantage – in our above example, I’m simply illustrating the concept by logging the result object on to the console window.

Update / Edit Document In MongoDB: Node.js


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

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



Full Source Code: with findByIdAndUpdate() method
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
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.get('/user/:id/edit', function(req, res){
res.render('edit-form', {user: req.userId});
});
 
app.put('/user/:id', function(req, res){
user.findByIdAndUpdate({_id: req.params.id},
                   {
     name: req.body.name,
  age   : req.body.age
   }, function(err, docs){
 if(err) res.json(err);
else
{ 
   console.log(docs);
   res.redirect('/user/'+req.params.id);
 }
 });
});
 
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'));
});

/ for new entries
/view for viewing all the users
/user/:id to see individual user information
/user/:id/edit to edit individual user information

Note:
In real-world applications, it would make sense if only you are allowed to edit and update your data. To accomplish this – once the user logs in, store her _id value in a session variable. While the user issues an edit/update for a particular id, make sure the id she is requesting for edit/update matches with that present in the session variable!

Forms Using Jade: Node.js

Forms are one of the important components of web application. You need registration form, login form, edit form, status update form etc ..

forms-in-Jade-nodejs

In this video tutorial we shall see how to write the form in Jade, and how to use Twitter Bootstrap to design the form (we just show you how to add the id or class tags and not actual bootstrap implementation – but if you need any help, you can always ask us in the comment section below).

Related Read:
Basics of Jade – Template Engine: Node.js
Loops and Conditions In Jade: Node.js
Mixins in Jade: Node.js

Route To Render Form
app.js

1
2
3
app.get('/edit', function(req, res){
 res.render('edit-form');
});

We define a route /edit and once someone visits this route, we render our edit-form.jade template file.

Form tags in Jade
edit-form.jade

1
2
3
4
5
6
7
8
9
10
form(method="POST", action="/user")
 input(type="hidden", name="_method", value="PUT")
 p Name
  input(type="text", name="name")
 p Email
  input(type="email", name="email")
 p Age
  input(type="number", name="age")
 p
  input(type="submit")

Here we indent input tags inside paragraph tags, which is a child of form. We separate form attributes using comma.

Forms Using Jade: Node.js


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

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



Form tags with Jade and Bootstrap
edit-form.jade

1
  input#btn(type="submit")

If you want to use bootstrap along with your jade template files, make sure to include bootstrap.min.css and bootstrap.min.js and jquery.min.js into your file, by opening layout.jade present inside your view folder. Now add the id or class names along with the html tags, this should render you bootstrap enabled functionality and styling.

Form output source code
view-source:localhost:3000/edit

1
2
3
4
5
6
7
<form method="POST" action="/user">
 <input type="hidden" name="_method" value="PUT"/>
 <p>Name<input type="text" name="name"/></p>
 <p>Email<input type="email" name="email"/></p>
 <p>Age<input type="number" name="age"/></p>
 <p><input type="submit"/></p>
</form>

You can observe the nesting of elements and their relationship – child and parent.

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