Save data To MongoDB: Node.js

After learning to connect our Node.js application to MongoDB, lets see how we could insert data into our database collection.

insert-into-mongoDB-nodejs

Note:
Save() is a higher lever method. It checks to see if the object we’re inserting is already present in our collection, by checking the _id value we’re inserting. _id field(which is a primary key in MongoDB document)
– If there is no matching _id field in a document, it’ll call insert method and insert the data. And if the data being entered has no _id value, insert() method will create _id value for us, and insert the data into the collection.
– If _id matches to any document in our collection, it’ll use update() instead to update the previously present data with the new data entered by the user.

Form To Facilitate User To Enter Her Details ..or 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>

Here we have 3 input fields(for email, name and age) and a submit button. Since we’re posting these data to /new (in the action field of the form), we need to create /new route.

Route To Process User Entries
app.js

1
2
3
4
5
6
7
8
9
10
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.send('Successfully inserted!');
});
});

By using bodyParser() middleware, we get the data from the form, parse it and assign the values to corresponding keys, by creating a new user.

Note: user is a model object in our example. We also chain save method with new user object. Save() method takes a callback method as argument. The callback method takes 2 arguments – error and document. We check, if there are any errors while inserting the data, if so, we output the error object on to the screen. If the insertion was successful, we display “Successfully inserted!” message.

Inserting data To MongoDB: Node.js


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

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



Related Read:
number Input Type: HTML5
Create and Insert Documents: MongoDB
MongoDB Tutorial List

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
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.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.send('Successfully inserted!');
});
});
 
 
 
var server = http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

Here we’ve shown the configurations, middleware, mongoose connection, schema, model object, routes and out application server.

Validating User Request: Node.js

Validating user requests is one of the key elements of a web application, and is critical for its performance.

validating-user-request

In this tutorial, we validate the user request against elements present inside an array. In real-time web applications, the request is validated against database values.

Validating User Request In Express: Node.js
app.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
var names = [
 "Satish",
 "Kiran",
 "Sunitha",
 "Jyothi"
];
 
app.param('username', function(req, res, next, username){
var flag = parseInt(names.indexOf(username), 10);
 
if(flag >= 0)
 next();
else 
 res.end("No Such User!");
});
 
app.get('/user/:username', function(req, res){
res.send("Viewing user: "+req.params.username);
});

when the user requests for data via the route /user/someUsername we check if the user is actually present. If he is present, we’ll serve the data or else we’ll send No Such User! message to the browser.

To keep the routes clean, we shift the code to app.param First parameter indicates to which route the app.param is bound to. The callback method takes a couple of arguments – request, response, next and the username the user has requested.

we make use of indexOf() method to check if the requested username is actually present in our array. If the element is present in the array, indexOf() returns its position or else it returns -1.
If it returns 0 or any other positive value, then call next() to pass the control to the next layer of execution or else, display No Such User! and end the response.

Validating User Request: Node.js


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

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



Note: Usually if you retrieve data out of a MongoDB server, the data will be present in the form of object( {key: value} pair ).

Validating User Request In Express: Node.js
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
var names = [
 {
"id"        :  1,
"name"   :  "Apple",
"product": "iPhone"
},
 {
"id"        :  2,
"name"   :  "Google",
"product": "Nexus"
},
 {
"id"        :  3,
"name"   :  "Technotip",
"product": "Education"
},
 {
"id"        :  4,
"name"   :  "Microsoft",
"product":  "Nokia Lumia"
}
];
var flag = undefined;
app.param('id', function(req, res, next, id){
 
for(var i = 0; i < names.length; i++ )
 if(names[i].id == id)
   flag = "<b>Company: "+names[i].name+
            "<br /><b>Product: </b>"+names[i].product;
 
if(flag != undefined)
  next();
else
        res.end("No Such User!");
});
 
app.get('/user/:id', function(req, res){
res.send(flag);
});

Here we have an array of objects. Once the user requests company information using company id(/user/:id), we check through each object’s id and if it matches we call next() or else send No Such User! to the browser.

some output
/user/0
No Such User!

/user/1
Company: Apple
Product: iPhone

/user/2
Company: Google
Product: Nexus

/user/4
Company: Microsoft
Product: Nokia Lumia

Home Work Combine today’s learning with Error handling and write complete code for user request validation as well as error handling using Error object.

Error Handling In Express: Node.js

User inputs are very unpredictable on the web. So error handling becomes very important while building any real-time web application.

error-handling-in-express-nodejs

Express facilitates very good support for error handling, with its connect middleware.

Page Not Found Error Handling In Express: Node.js
app.js

1
2
3
4
5
6
7
8
9
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
app.use(function(req, res){
res.send(404, "Not found :-(");
});
 
app.get('/', function(req, res){
res.send("Homepage!");
});

When the user visits root of the website ( / ), a message called “Homepage!” is displayed to the user. But what if he tries to access a URL route which is not defined Ex: /user It displays Cannot GET /users message. We can set up a separate middleware to deal with situations like this. When we encounter a URL which doesn’t have a custom route definition, it’ll look for the file in the public directory, if the file is not found, it’ll look through our final middleware and executes whatever is present inside it.

User Not Found Error Handling In Express: Node.js
app.js

1
2
3
4
5
6
7
8
9
10
11
12
13
app.use(function(err, req, res, next){
res.send(404, err.message);
next();
});
 
app.get('/user/:username', function(req, res, next){
if(req.params.username === 'kiran')
{
var err = new Error('User Not Found');
next(err);
}
res.send(req.params.username);
});

In real world application, we need to validate the user request before trying to serve them data. Here, if the user requests /user/kiran we’ll let the user know that the user kiran is not present in our database. So we setup a custom error handling middleware for situations like this. Here we create an error object and set a message, and pass this error object as parameter to next. call to next passes the control to the middleware which matches its signature, and executes whatever is present inside the middleware. [ Note the presence of err object inside the middleware callback method. ]

Error Handling In Express: Node.js


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

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



Note: Error handling can significantly increase the performance of your web application, due to the fact that your application need not figure out what to do next, in case of an error. You explicitly write error handling code for most common situations and the application behaves in a predictable manner.

Call to next() passes the execution control to the next level.

Sessions In Express: Node.js

After learning about cookies, lets look briefly about sessions in Express applications.

sessions-express-nodejs

If you’ve ever worked on any serious web application, you already know the importance of session. Creating session for logged in users, tracking the shopping cart items, storing the URL for redirect etc are some of the basic uses of sessions.

session middleware in Express: Node.js
app.js

1
2
3
4
5
6
var express = require('express');
 
var app = express();
 
app.use(express.cookieParser());
app.use(express.session({secret: 'some secret key'}));

session middleware needs cookieParser() because session objects lookup for the cookie for matching up the requests.

setting session variable in Express: Node.js
app.js

1
2
3
4
app.get('/user/:user', function(req, res){
req.session.name = req.params.user;
res.send('<p>Session Set: <a href="/user">View Here</a></p>');
});

session is present inside request object. So assign the string or the value to req.session.sessionName

Fetching session value in Express: Node.js
app.js

1
2
3
4
5
6
app.get('/user', function(req, res){
if(req.session.name)
 res.send(req.session.name+'<br /><a href="/logout">Logout</a>');
else
 res.send('user logged out!');
});

Here we check if the req.session.name has been set. If set, we show link to logout and also show current value present in the session variable. If the user is coming from /logout page, then we show “user logged out!” message.

destroy session value in Express: Node.js
app.js

1
2
3
4
app.get('/logout', function(req, res){
req.session.destroy();
res.send('<br />logged out!<br /><a href="/user">Check Session</a>');
});

Once the user clicks on /logout we destroy all the session by using req.session.destroy() We also give link to /user page, to check the fact that the session has already been destroyed.

Sessions In Express: Node.js


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

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



Note: Make sure to have good session secret key – a combination of alphanumeric plus special characters. And make sure not to reveal it to anyone. Because, using this secret key / hash, someone with bad intention could possibly revoke the session and use your application as an authentic user, if care is not taken!

The main difference with cookie and a session is – session is stored on the server side and cookie on the client side.

Cookies In Express: Node.js

Cookies are one of the important recipe for building an effective web application.

cookies-express-nodejs

A cookie, also known as an HTTP cookie, web cookie, or browser cookie, is a small piece of data sent from a website you are surfing and stored in a user/client computer. Every time the user loads that website again, the browser sends this cookie back to the server to notify the website of the user’s previous activity.

This way, using cookie, we could track user activities like her navigational behaviors, previous purchases on our site or previous leads etc.

Setting Cookie in Express: Node.js
app.js

1
2
3
4
5
6
7
8
9
10
var express = require('express');
 
var app = express();
app.use(express.cookieParser());
 
app.get('/user/:user', function(req, res){
res.cookie('username', req.params.user)
    .send('<p>Cookie Set: <a href="/user">View Here</a>');
});
</p>

Using express’s cookieParser() middleware we can enable working with cookies.
Once the user navigates to /user/someUserName URL, the cookie is set with the name username and the value is actually fetched out of the request object’s params.

General Syntax for setting Cookie

res.cookie('cookieName', value, {expires: new Date() + 99999, maxAge: 99999});

Set a name to the cookie, give it some value. Also you can set the optional settings like, expiration date or the maxAge the cookie will be alive on the client computer.

Accessing Cookie in Express: Node.js
app.js

1
2
3
app.get('/user', function(req, res){
res.send(req.cookies.username);
});

Once the user visits /user route, we fetch the value present in the req.cookies.username and display it to the user.

Cookie In Express: Node.js


[youtube https://www.youtube.com/watch?v=mdvQ74KL-fU]

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



Note: We could see the value stored in a cookie, by using chrome’s console window and typing document.cookie

Clearning Cookie in Express: Node.js
app.js

1
2
3
4
app.get('/user', function(req, res){
res.clearCookie('username')
           .send(req.cookies.username);
});

You could remove a cookie by using clearCookie method of response object.

Once the cookie has been removed, you can set it again explicitly using Chromes console window.
Type: document.cookie = “username = Microsoft”
now refresh the browser, and you’ll see Microsoft being displayed!