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.
== 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 !===
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
$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
$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.
<h1>#{user.name}</h1>
ul
li Age: #{user.age}
li Email: #{user._id}
ul
li
a(href="/user/#{user._id}/delete") Delete
<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');
});
});
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');
});
});
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
<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');
});
});
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');
});
});
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.
ul
each user in users
li
a(href='/user/#{user._id}') #{user.name}
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")
<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
<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
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'));
});
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.
ul
each user in users
li
a(href='/user/#{user._id}') #{user.name}
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
<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")
<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.
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.
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.
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'));
});
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 are one of the important components of web application. You need registration form, login form, edit form, status update form etc ..
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).
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")
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.
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
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.
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.
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.
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.