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.

number Input Type: HTML5

number input type indicates that the input field is used for entering numbers.

form-input-type-number-type-html5

Advantages of using number input type:
1. Browsers which support HTML5, provides useful user interface enhancement by providing up and down arrow/tickers to increment and decrement the number.
2. You get a customized keyboard which is optimized for numeric inputs on mobile devices which supports number input type.
3. Using attributes like min, max and step, you can have more control. You can specify the minimum, maximum values the field takes and also you can specify the step for incrementing and decrementing the number using arrow marks.
4. Basic validation to check if the user entered numeric value or not.

HTML file
index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
< !DOCTYPE html>
<html>
<head>
<title>number Input Type: HTML5</title>
<link href="myStyle.css" rel="stylesheet" />
</head>
<body>
 
<form>
<label for="no">Number: </label>
 <input name="no" type="number" value="5" min="2.0" max="10.0" step="0.2" />
 <input type="submit"/>
</form>
 
</body>
</html>

Here we have a number input type, with minimum allowed value of 2.0 and a maximum allowed value of 10.0 and a step of 0.2 (fraction).

CSS file associated with this is same as present at pattern and title Attribute of Form Field: HTML5

Form Input Type – number: HTML5


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

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



Note: Browsers which do not support number input type, simply fall back to text input type, so you can go ahead and implement number input type in your projects without worrying. It’s a good practice to even validate the code at server-side, since browsers can be easily tricked and wrong entries can be made using form elements.

Email Input Type: HTML5

Lets look at email input type of HTML5 forms.

form-input-type-email-type-html5

In this video, we illustrate how you can implement simple email validation using email input type.

HTML file
index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
< !DOCTYPE html>
<html>
<head>
<title>Email input type: HTML5</title>
<link href="myStyle.css" rel="stylesheet" />
</head>
<body>
 
<form>
<label for="mail">Email: </label>
 <input type="email"/><br />
 <input type="submit"/>
</form>
 
</body>
</html>

Here we have an input field of type email. We haven’t implemented complicated JavaScript to check if the entered text actually contains a @ symbol and a valid TLD. email input type checks for all these small requirements to pass it as an email address.

Form Input Type – email: HTML5


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

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



Note:
It doesn’t validate the email address completely. Infact, it doesn’t check if the entered email address is actually a real email address or a dummy one. It simply checks for minimal thing in the entered text to determine if it is an email address or not – like @ symbol and a valid TLD(Top Level Domain) extension.

Also on mobile devices, when it encounters these email input type, user is prompted with keypad that aids in entering email address – like the @ symbol present on the same screen and need not to navigate to special symbols section on the keypad.

require attribute: HTML5

Lets see how require attribute of HTML5 works.

require attribute forces the user to enter some value. But it does not validate the user input.
Example: It makes sure if the email field has some value in it but doesn’t check if the user has entered valid email address or not. It only makes sure, the required field isn’t left empty.

require-form-field-attribute-html5

HTML file
index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
< !DOCTYPE html>
<html>
<head>
<title>required attribute: HTML5</title>
<link href="myStyle.css" rel="stylesheet"/>
</head>
<body>
 
<form>
<label for="name">Name: </label>
 <input type="text" name="name" required/><br />
 
<label for="age">Age: </label>
 <input type="text" name="age"/><br />
 
 <input type="submit"/> 
</form>
 
</body>
</html>

Here we have 2 input fields. First input field has been made required, by using require attribute.

CSS file associated with this is same as present at pattern and title Attribute of Form Field: HTML5

require attribute: HTML5


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

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



Note:
Server side validation is also equally important. Because someone might directly pass the value via the script present in the action field of form tag – if form uses GET method to pass user data.

Also note that, IE(Internet Explorer) doesn’t support require attribute, so you can make use of Javascript or jQuery to make sure IE users are taken care of.
Related Read: Registration Form Validation: PHP + jQuery + AJAX

Form novalidate attribute: HTML5

Today let us learn about novalidate and formnovalidate attributes of HTML5 form.

form-novalidation-html5

In this video tutorial I’m taking 2 input fields and making one input field as required. Also take 2 submit buttons, with one validating the user entered data and the other one bypassing the validation rules set.

HTML file: formnovalidate
index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
< !DOCTYPE html>
<html>
<head>
<title>novalidation: HTML5</title>
<link href="myStyle.css" rel="stylesheet"/>
</head>
<body>
 
<form>
<label for="name">Name: </label>
 <input type="text" name="name" required/><br />
 
<label for="age">Age: </label>
 <input type="number" name="age"/><br />
 
<input type="submit" value="Submit"/>
<input type="submit" value="Save" formnovalidate/>
</form>
 
</body>
</html>

Here we are using formnovalidate attribute on submit button which has a value of Save. This button bypasses the validation rules.

HTML file: novalidate
index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
< !DOCTYPE html>
<html>
<head>
<title>novalidation: HTML5</title>
<link href="myStyle.css" rel="stylesheet"/>
</head>
<body>
 
<form novalidate>
<label for="name">Name: </label>
 <input type="text" name="name" required/><br />
 
<label for="age">Age: </label>
 <input type="number" name="age"/><br />
 
<input type="submit" value="Submit"/>
</form>
 
</body>
</html>

Here I’ve added novalidate attribute directly to the form tag, which bypasses any validation rules written to it or to it’s child elements/tags.

CSS file associated with this is same as present at pattern and title Attribute of Form Field: HTML5

novalidate and formnovalidate attributes of HTML5 form


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

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



Why would we ever need novalidation for forms ?
Sometimes we enter a lengthy form and submit, but due to some validation mistakes all our entries gets erased, and the user may not have the patience to re-enter everything from beginning. He may skip it altogether. To avoid that, you can build an interface wherein user can save her data first and then can submit it after reviewing it. In such a situation we can make use of a temporary database table to store user entered information and display for review with appropriate messages to correct the wrong inputs – user can correct them and Submit.