This is a basic example wherein we have a list of company names and once the user clicks on individual name, that name gets removed from the list. We’ve not included the http calls and database in this example to keep things simple and minimalistic.
Here we have an array variable called companies, which has 5 company names in object format. We also have a method called remove which takes 1 parameter. This parameter is the index number of the item being clicked by the user. Once we get this index number we make use of JavaScript’s splice() method and remove the element from the array. Splice takes 2 arguments, the first one being the index(or the position) of the element to be removed and the second argument is the number of elements to be removed from position of the index received.
src/pages/home/home.html
< ion-list no-lines>
< ion-item *ngFor="let company of companies;
let i = index;"
(click)="remove(i);">
{{company.name}}
< /ion-item>
< /ion-list>
< ion-list no-lines> < ion-item *ngFor="let company of companies; let i = index;" (click)="remove(i);"> {{company.name}} < /ion-item>
< /ion-list>
Here we assign index value to a variable i. We then pass this value of i to remove method once the user clicks on an item. i.e., we pass the index value of the item being clicked by the user, to the remove method.
Real-time Applications In real-time applications we’ll pass a unique id of the clicked element to the remove method, which is then passed on to some http calls, which removes the item from the database(usually) and if the remove operation is successful we’ll remove the item from the User Interface using JavaScripts Splice() method. And if the remove operation fails, we’ll display appropriate message to the user.
Since “names” collection was empty, we inserted 2 documents into it. Now we applied drop() method on the collection, which drops all the document present in the collections at once. It also removes the document/index/content present inside “system.indexes” collection.
Note: If you want to remove/drop all the documents present inside the collection, make use of drop() method, as it removes all the documents at once, its more efficient than remove({}) method which removes documents one by one. Use remove() method, when you want to remove one or a set of documents from the collection.
<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.
This video tutorial illustrates searching, installing, updating and removing the external, free modules.
External Free Node Modules are listed at npmjs.org and is managed by NPM – Node Package Manager.
There are so many amazing modules already written to handle so many sophisticated functionalities, that it becomes easy to use them in our application and build a robust, scalable application quickly.
Command to look at all the external module names and their respective description
1
npm search
npm search
It gives a long list of names and descriptions.
To make is look better, you can use GREP(if you’re on Linux or Unix based System) Search with GREP
1
npm search | grep module_name
npm search | grep module_name
npm search followed by pipe symbol, which is followed by any module name.
For Windows users
1
npm search module_name
npm search module_name
it gives all the details of available methods, properties and their description.
Installation of Modules
init command
1
npm init
npm init
Once you run this command, it prompts you with some optional things, like, name of the project, version, author, licensing etc. Once you’re done with that, it creates package.json file with all the details you provided.
The ‘init’ command in NPM allows us to identify our project and list out any Node Modules it requires.
Now open that package.json file: it looks somewhat like this package.json file
You need to open this package.json file using a plain text editor and add your project dependencies i.e., some of the modules you need to install for your project.
In this video tutorial we’re installing 3 external modules: express jade mongoose
What is a module? A module is a self-contained series of one or more javascript files represented by an object.
Update Command
1
npm update
npm update
once you run this command, package.json file is parsed and the dependency modules are checked for any updates, if any, it’ll be updated. If any module is installed with -g (global scope), i.e., the root installation, then while updating or removing them, it may throw some errors, in such case, use sudo keyword:
Update Command
1
sudo npm update -g
sudo npm update -g
This would solve the problem both for updating and deleting external modules.
remove/delete module command
1
npm prune
npm prune
To remove the unused modules: open package.json file and remove the module names which you want to remove. Save the package.json file and then run above(npm prune) command. This would safely remove the modules you no more intend to use in your project.
List Global module: using command
1
npm -g ls
npm -g ls
This lists all the global modules, it’s path and file structure: as shown below:
Assume that a client has mailed her requirements to us: She has 5 images in her html page. Once the user clicks on a image, a message should popin beside the image. Image should be clickable only once. Once the user clicks on other images, the messages appended beside previously clicked image must be removed.
With these requirements in mind, we shall start developing our image based jQuery Application.
Once the document is ready and the user clicks on a image: 1. Any b tag present in the document is removed. Thus, the message associated with the image which was being clicked previously is removed. 2. The parent tag of the image being clicked: i.e., div tag is selected and a message with b tag is appended to it, which appears beside the image being clicked by the user. 3. The event associated with the image being clicked is removed.
Note: Use of function().function() is called chain method. Example: parent().append(); next().parent().remove(); etc
Make sure to maintain the order of the code. If you replace or rearrange the code in a way other than above, you wouldn’t get expected result. While practicing, change the order of the code and look for the output, that would help you understand the code and the flow / execution flow well.
Video Tutorial: Working With Images: Small jQuery Application