Update with UNSET Operator: MongoDB

Lets use $unset operator along with update() method, to update the documents.

update with set operator mongodb Update with UNSET Operator: MongoDB

test database, names collection

1
2
3
4
5
6
7
8
9
10
11
12
13
> db.names.find().pretty()
{
        "_id" : ObjectId("53c3fc2005e0ce2719d91bd2"),
        "Company" : "Google",
        "Product" : "Nexus",
        "No" : 1
}
{
        "_id" : ObjectId("53c3fd3bb9ae26fa217b1e12"),
        "Company" : "Apple",
        "Product" : "iPhone",
        "No" : 2
}

Here we have 2 documents with fields _id, Company, Product and No.

Update with UNSET Operator: MongoDB


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

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



We could remove a field using update() method, by not specifying it in the second argument.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
> db.names.update({"No": 1}, {"Company": "Google", "No": 1});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
 
> db.names.find().pretty()
{
        "_id" : ObjectId("53c3fc2005e0ce2719d91bd2"),
        "Company" : "Google",
        "No" : 1
}
{
        "_id" : ObjectId("53c3fd3bb9ae26fa217b1e12"),
        "Company" : "Apple",
        "Product" : "iPhone",
        "No" : 2
}

Related Read: Update Method: MongoDB

This way, we could eliminate the field Product. But this is a tedious process – we need to remember all the fields inorder to achieve this. It gets difficult when we have many fields in our document. To solve this problem, we have $unset operator, where we only need to know the field name which we want to remove.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
> db.names.update({"No": 1}, {$unset: {"Product": 1}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
 
> db.names.find().pretty()
{
        "_id" : ObjectId("53c3fc2005e0ce2719d91bd2"),
        "Company" : "Google",
        "No" : 1
}
{
        "_id" : ObjectId("53c3fd3bb9ae26fa217b1e12"),
        "Company" : "Apple",
        "Product" : "iPhone",
        "No" : 2
}

$unset operator syntax is same to unset or remove array from a document.

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
> db.names.update({"No": 1}, {$set: {"Product": ["LG", "Samsung", "HTC"]}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
 
> db.names.find().pretty()
{
        "_id" : ObjectId("53c3fc2005e0ce2719d91bd2"),
        "Company" : "Google",
        "No" : 1,
        "Product" : [
                "LG",
                "Samsung",
                "HTC"
        ]
}
{
        "_id" : ObjectId("53c3fd3bb9ae26fa217b1e12"),
        "Company" : "Apple",
        "Product" : "iPhone",
        "No" : 2
}
 
> db.names.update({"No": 1}, {$unset: {"Product": 1}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
 
> db.names.find().pretty()
{
        "_id" : ObjectId("53c3fc2005e0ce2719d91bd2"),
        "Company" : "Google",
        "No" : 1
}
{
        "_id" : ObjectId("53c3fd3bb9ae26fa217b1e12"),
        "Company" : "Apple",
        "Product" : "iPhone",
        "No" : 2
}

Related Read: Update with SET Operator: MongoDB

Update with SET Operator: MongoDB

Lets use $set operator along with update() method, to update the documents.

test database, names collection

1
2
3
> db.names.find()
{ "_id" : ObjectId("53be5d4604cc1cb0a7bfc3c0"), "name" : "Alia" }
{ "_id" : ObjectId("53be5d5204cc1cb0a7bfc3c1"), "name" : "Bebo" }

update-with-set-operator-mongodb

Related Read: Update Method: MongoDB

Lets update the first document using only update method.

1
2
3
4
5
6
7
8
9
10
> db.names.update({"name": "Alia"}, {"name": "Alia", "age": 25});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
 
> db.names.find().pretty()
{ "_id" : ObjectId("53be5d5204cc1cb0a7bfc3c1"), "name" : "Bebo" }
{
        "_id" : ObjectId("53be5d4604cc1cb0a7bfc3c0"),
        "name" : "Alia",
        "age" : 25
}

Everything is ok in this case. But what if you forget to mention the name field in the second argument of update() method.

1
2
3
4
5
6
> db.names.update({"name": "Alia"}, {"age": 25});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
 
> db.names.find().pretty()
{ "_id" : ObjectId("53be5d5204cc1cb0a7bfc3c1"), "name" : "Bebo" }
{ "_id" : ObjectId("53be5d4604cc1cb0a7bfc3c0"), "age" : 25 }

In this case, the name field gets erased. As we did not specify name field in the second parameter of update() method.

Using $set operator

1
2
3
4
5
6
7
8
9
10
> db.names.update({"name": "Bebo"}, {$set: {"age": 25}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
 
> db.names.find().pretty()
{ "_id" : ObjectId("53be5d4604cc1cb0a7bfc3c0"), "age" : 25 }
{
        "_id" : ObjectId("53be5d5204cc1cb0a7bfc3c1"),
        "name" : "Bebo",
        "age" : 25
}

Here we make use of document with name as Bebo. Using $set operator we only specify the fields we want to add or update. Need not specify other existing fields in order to retain them.

Update with SET Operator: MongoDB


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

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



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
> db.names.update({"name": "Bebo"}, {$set: {"age": 25, "salary": 25}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
 
> db.names.find().pretty()
{ "_id" : ObjectId("53be5d4604cc1cb0a7bfc3c0"), "age" : 25 }
{
        "_id" : ObjectId("53be5d5204cc1cb0a7bfc3c1"),
        "name" : "Bebo",
        "age" : 25,
        "salary" : 25
}
 
 
> db.names.update({"name": "Bebo"}, {$set: {"age": 26, "salary": 25}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
 
> db.names.find().pretty()
{ "_id" : ObjectId("53be5d4604cc1cb0a7bfc3c0"), "age" : 25 }
{
        "_id" : ObjectId("53be5d5204cc1cb0a7bfc3c1"),
        "name" : "Bebo",
        "age" : 26,
        "salary" : 25
}
 
 
> db.names.update({"name": "Bebo"}, {$set: {"salary": 30}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
 
> db.names.find().pretty()
{ "_id" : ObjectId("53be5d4604cc1cb0a7bfc3c0"), "age" : 25 }
{
        "_id" : ObjectId("53be5d5204cc1cb0a7bfc3c1"),
        "name" : "Bebo",
        "age" : 26,
        "salary" : 30
}

We can update existing field or add a field to the existing document using $set operator and need not to worry about the other fields in the document.

Update Method: MongoDB

Lets learn how to update MongoDB document using update() method.

test database, names collection

1
2
3
4
5
6
> db.names.find().pretty()
{
        "_id" : ObjectId("53c3c4b1a0eddb0a706e4f56"),
        "name" : "Satish",
        "age" : 27
}

Observe the document, with fields name and age. We’ll be illustrating update() method by working on this document.

update-method-mongodb

1
2
3
4
5
> db.names.update({"name": "Satish"}, {"age": 28});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
 
> db.names.find().pretty()
{ "_id" : ObjectId("53c3c4b1a0eddb0a706e4f56"), "age" : 28 }

update() method takes at least 2 arguments. First argument being the condition(WHERE clause in sql) and the second argument being the fields to be updated. Observe that, whatever the fields we specify in the second argument are only retained(along with _id), all other fields will be erased.

1
2
3
4
5
6
7
8
9
> db.names.update({"age": 28}, {"name": "Satish", "age": 28});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
 
> db.names.find().pretty()
{
        "_id" : ObjectId("53c3c4b1a0eddb0a706e4f56"),
        "name" : "Satish",
        "age" : 28
}

Now we’ve updated with name as well as age field and it reflects in the document in the collection.

Update Method: MongoDB


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

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



1
2
3
4
5
6
7
8
9
10
> db.names.update({"age": 28}, {"name": "Satish", "age": 28, "salary": 200000});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
 
> db.names.find().pretty()
{
        "_id" : ObjectId("53c3c4b1a0eddb0a706e4f56"),
        "name" : "Satish",
        "age" : 28,
        "salary" : 200000
}

If we want to update/add a new field to the document, we must also specify all other fields we want to retain in the document.

1
2
3
4
5
> db.names.update({"age": 28}, {"salary": 300000});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
 
> db.names.find().pretty()
{ "_id" : ObjectId("53c3c4b1a0eddb0a706e4f56"), "salary" : 300000 }

If we forget to specify other fields, then they will be erased(except _id field).

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!

External Module( NPM ) Install, Update, Remove: Node.js

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 NPMNode 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

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 followed by pipe symbol, which is followed by any module name.

For Windows users

1
npm search module_name

it gives all the details of available methods, properties and their description.

Installation of Modules

init command

1
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

1
2
3
4
5
6
7
8
9
10
11
12
{
  "name": "app",
  "version": "0.0.0",
  "description": "authentication application",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": "",
  "author": "SATISH B",
  "license": "BSD"
}

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

package.json file, after editing

1
2
3
4
5
6
7
8
9
10
11
12
13
{
  "name": "app",
  "version": "0.0.0",
  "description": "authentication application",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
 "dependencies": { "express": "2.5.8", "jade": "0.26.1", "mongoose": "2.6.5" },
  "repository": "",
  "author": "SATISH B",
  "license": "BSD"
}

Now you’ve specified all the external modules your project depends on.

Now using install command, we need to install these modules.
installation command

1
npm install

Once this command is executed, it looks through the package.json file and installs all the dependency modules one by one.

External Module Install, Update, Remove via NPM: Node.js


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

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



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

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

This would solve the problem both for updating and deleting external modules.

remove/delete module command

1
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

This lists all the global modules, it’s path and file structure: as shown below:

Example output

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
C:\node\express_example>npm  -g ls
C:\Users\Satish\AppData\Roaming\npm
└─┬ [email protected]
  ├── [email protected]
  ├─┬ [email protected]
  │ └── [email protected]
  ├─┬ [email protected]
  │ ├── [email protected]
  │ ├─┬ [email protected]
  │ │ ├── [email protected]
  │ │ └── [email protected]
  │ ├── [email protected]
  │ ├── [email protected]
  │ └── [email protected]
  ├── [email protected]
  ├── [email protected]
  ├── [email protected]
  ├── [email protected]
  ├── [email protected]
  ├── [email protected]
  ├── [email protected]
  └─┬ [email protected]
    └── [email protected]

Removing/Uninstalling Global modules: using command

1
npm -g rm

This removes all the global modules installed.

Clear cache

1
npm cache clear

After modifiying things from command prompt, if it’s still not working, try clearing the cache.

Note:
To install latest version of the module: you’ll need to write * (asterisk or star) in the place of version number inside package.json file.