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
1
2
3
4
5
6
7
You can observe the nesting of elements and their relationship – child and parent.
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.
What’s the use of the data in database, if we can’t fetch it and display on a web page! Today’s video tutorial concentrates on fetching data out of our mongoDB collection and displaying it on the web page.
Once the user visits /view route, she will be presented with all the registered users information. Inside /view route, we fetch all the user information by using mongoDB’s find() method. find() takes 2 parameters – first parameter is an object with condition, second parameter is a callback method. If we pass in empty object as first parameter, it means, fetch all the data – similar to SELECT * in sql.
If find() could successfully fetch the data out of mongoDB collection, it renders index.jade file and passes an object to it – which contains information of all the fetched users.
Template To Display User Information view/index.jade
1
2
3
ul
each user in users
li #{user.name}: #{user.age}: #{user._id}
ul
each user in users li #{user.name}: #{user.age}: #{user._id}
Observe the find() methods first parameter. Now we are passing _id to it, which means, it has to find and retrieve only the information related to the user with that _id.
Full Code To Insert And Fetch Data into/from MongoDB 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.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('/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'));
});
To make this work, go to Save data To MongoDB: Node.js tutorial page and copy the index.html page code and create one for your project and put it inside public directory. Now you can directly access root(html form), enter user information and submit, which redirects to /view route, wherein you get the information of all the registered users.
Note: Make sure MongoDB server is running and turned on, when you start Node.js server and access your application from web browser.
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>
Registration Form
< !DOCTYPE html>
Registration Form
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.
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.
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'));
});
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.
In today’s video tutorial lets learn to connect to MongoDB server from our Node.js application using Mongoose module.
Mongoose Module Mongoose provides a straight-forward, schema-based solution to modeling your application data and includes built-in type casting, validation, query building, business logic hooks and more..
list the mongoose module as a dependency for your Node.js application
Install the dependencies
1
npm install
npm install
This looks for all the dependencies listed in package.json file and installs it. Make sure that your system is connected to the internet.
Connecting to MongoDB app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
var mongoose = require('mongoose');
app.use(express.bodyParser());
app.use(express.methodOverride());
mongoose.connect('mongodb://localhost/Company');
var mySchema = new mongoose.Schema({
_id : String,
name: String,
age : Number
});
var user = mongoose.model('emp', mySchema);
var mongoose = require('mongoose');
app.use(express.bodyParser());
app.use(express.methodOverride());
mongoose.connect('mongodb://localhost/Company');
var mySchema = new mongoose.Schema({
_id : String,
name: String,
age : Number
});
var user = mongoose.model('emp', mySchema);
We have to first include mongoose module into our application. We also need the help of bodyParser() and methodOverride() middlewares in order to parse the form variables and override method to make PUT and DELETE methods work.
Next we connect to mongobd using connect method of mongoose module. Here we also specify the mongoDB database name to which our application will be connecting to. If the database is not already present, this will create one for us.
Next, we write a schema definition for our collection. Mongoose uses schema for validation of user entered data. By specifying the data type for our field we can make sure user entries are validated against the data types we have mentioned in our schema.
Some valid Schema Types, supported by Mongoose String Number Date Buffer Boolean Mixed Objectid Array
Mongoose Model A model in mongoose is an object that gives us easy access to a named collection, allowing us to query the collection and use the schema to validate any document we save to that collection.
Note 1: In above example code, we are creating a collection called emp and binding it with the schema mySchema
In above example Database name: Company Collection/table name: emp
Note 2: Make sure MongoDB server is up and running, before you execute your Node.js application.
Checking If your application succesfully connected to MongoDB Server! app.js
1
2
3
4
5
var db = mongoose.connection('mongodb://localhost/Company');
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback () {
// all your database operations(CRUD) here
});
var db = mongoose.connection('mongodb://localhost/Company');
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback () { // all your database operations(CRUD) here
});
Here by using on method we check if we could successfully connect to our mongoDB server. If there was any error, we output the error on to the screen. If the connection is successful, we’ll continue with our CRUD operations on the database tables.