58
Introduction to node.js … and Express, Jade, mongoDB, mongoose February 2013

Introduction to node.js

Embed Size (px)

DESCRIPTION

A quick introduction to node.js in order to have good basics to build a simple website. This slide covers: - node.js (you don't say?) - express - jade - mongoDB - mongoose

Citation preview

Page 1: Introduction to node.js

Introduction to node.js

… and Express, Jade, mongoDB, mongoose

February 2013

Page 2: Introduction to node.js

The "teacher"

SUPINFO

B1 – B2 Caen (France)

B3 San Francisco (California)

M1 – M2 London (UK)

Web developer

Global Lab Manager of SUPINFO Web Laboratory

Games oriented developer and Vanilla JavaScript lover

http://adriengueret.no-ip.org/

https://twitter.com/AdrienGueret

Page 3: Introduction to node.js

A busy program

Some JavaScript revisions

Look at node.js

Discovery of Express framework

HTML templates with Jade

NoSQL and mongoDB

Using databases with mongoose

Page 4: Introduction to node.js

JavaScript remindersIt could be useful…

Page 5: Introduction to node.js

Functions are variables like other

//We store a function

var hello = function (name) {

alert('Hello ' + name + '!');

};

//We call this variable-function !

hello('World'); //Display«Hello World!»

Page 6: Introduction to node.js

Go further…

//A function with a function as parameter…

var callFunction = function (callback) {

callback('World');

};

callFunction(hello);

//Also display«Hello World!»

Page 7: Introduction to node.js

JSON format

var user = {

"first_name": "Jean",

"last_name": "Peplu",

"age": 22

};

alert('Hello ' + user.first_name + '!');

// «Hello Jean!»

Page 8: Introduction to node.js

JavaScripts objects

var user = {

first_name: "Jean",

last_name: "Peplu",

sayHello: function () {alert('Hello ' + this.first_name +

'!');}

};

user.sayHello(); // «Hello Jean!»

Page 9: Introduction to node.js

Discovery of node.jsA wonderful technology!

Page 10: Introduction to node.js

A young technology

Created by Ryan Dahl in 2009

Current version: 0.8.21

A "package" containing V8 JavaScript engine

Allow us to develop server-side with JavaScript!

Page 11: Introduction to node.js

Let’s install node.js!

Go to: http://nodejs.org/

Click on Install

Page 12: Introduction to node.js

What has been installed

Page 13: Introduction to node.js

A simple Web servervar http = require('http'),

port = 1337,

server = http.createServer(function (request, response) {

response.writeHead(200, {'Content-Type': 'text/plain'});

response.end('Hello World!');

});

server.listen(port);

//A nice log in the terminal

console.log('Server listening at port ' + port + '.');

>node server.js

Page 14: Introduction to node.js

request and response are useful parameters

request Give some information about HTTP request request.method, request.url…

response Send information to the client response.writeHead()…

Read the doc! http://nodejs.org/api/http.html

Page 15: Introduction to node.js

Your turn!

Create a basic Web server

3 different pages Home page when visitor is on the root of your

server

A test page on the URL /test

An error page (404) otherwise

Page 16: Introduction to node.js

Using ExpressFor a more efficient development!

Page 17: Introduction to node.js

What is Express?

Web application framework Current version: 3.0

http://expressjs.com/

Very simple installation:

Page 18: Introduction to node.js

Previous exercise with Expressvar port = 1337,

express = require('express'),server = express(),writePage = function (title, body) {

//We admit this function returns an HTML string

};

server.get('/', function (req, res) {

res.send(200, writePage('Home', 'Welcome home!'));

}).get('/test', function (req, res) {

res.send(200, writePage('Test page', 'It works!'));

}).listen(port);

Page 19: Introduction to node.js

Retrieve GET parameters

//Listen for localhost:1337/farms/?id=Xserver

.get('/farms/', function (req, res) {res.writeHead(200, {'Content-Type':

'text/plain'});res.end(Farm id: #' + req.query.id);

});

We get values thanks to req.query[parameter name]

Page 20: Introduction to node.js

Sexier: parameters in the URL

//Listen for localhost:1337/farms/X

server.get('/farms/:id', function (req, res) {

res.writeHead(200, {'Content-Type': 'text/plain'});

res.end(Farm id: #' + req.params.id);});

: + parameter name We get values thanks to req.params[parameter name]

Page 21: Introduction to node.js

Retrieve POST parameters

server.post('/farms/add', function (req, res) {

res. send(200, 'Nom reçu : ' + req.body.farm_name);

});

Tell the server we want to get these parameters:

We’ll use the post() method (no longer get()) We get values thanks to req.body[parameter name]

server.use(express.bodyParser());

Page 22: Introduction to node.js

Public files

server.use(

'/static',express.static( __dirname + '/public')

);

Also called "static" files Images, CSS, JavaScript…

How to link them with our HTML files? Put them in a folder name /public (or another name, it’s your choice!)

Find an alias (once again, you choose which one!) to this folder Indicate the use of this alias to serve this folder

Page 23: Introduction to node.js

Diagram of a typical case

Main server

Manages the HTTP server

The visitor

Requests

Works withSends therequested

information

Page 24: Introduction to node.js

The arrival of JadeBecause HTML is too complicated…

Page 25: Introduction to node.js

Jade

HTML template http://jade-lang.com/

Another simple installation:

Documentation: https://github.com/visionmedia/jade#a6 Interactive doc:

http://naltatis.github.com/jade-syntax-docs/

Page 26: Introduction to node.js

Why using a template?

To be more with the spirit of MVC architecture "Cleaner" code

doctype 5

html(lang="en")

head

title My page title

body

h1#title Jade - node template engine

p.desc Hello World! <br />

img(src="/static/images/ocarina.png")

Page 27: Introduction to node.js

Call a Jade template with Express

Put .jade files in the folder /views Tell the server to use Jade engine Call render() to display a .jade file

server.engine('jade', require('jade').__express).get('/', function (req, res) {

res.render('./sample.jade');//Path of the file :

/myProject/views/sample.jade });

Page 28: Introduction to node.js

Display variables with Jade Send variables thanks to the method render():

With Jade: use the #{variable_name} syntax:

server.get('/farms/:id', function (req, res) {

res.render('./farm_details.jade', { "farm_name" : "My wonderful farm", "farm_value" : 30000

});});

h1 #{farm_name}

p Value of this farm is:

strong #{farm_value}

Page 29: Introduction to node.js

Display a list of values

In Jade: use the each … in syntax:

server.get('/farms/', function (req, res) {

res.render('./all_farms.jade', { "all_farms_id" : [1, 6, 15, 21, 34, 42,

55]});

});

ul

each farm_id in all_farms_id

li Farm ##{farm_id}

Page 30: Introduction to node.js

Your turn! Install Express

Install Jade

Create a “Register user” form This form must redirect to its own page It sends data with POST method The target page just displays sent data

Oh, and please display a nice picture

Page 31: Introduction to node.js

HTML template

Asks for a template

Send HTML

Diagram of a typical case

Main server

Manages the HTTP server

The visitor

Requests

Works withSends therequested

information

Page 32: Introduction to node.js

A database with mongoDBForget SQL, long live NoSQL!

Page 33: Introduction to node.js

What is mongoDB?

A document-oriented database

Use the JSON format

http://www.mongodb.org/

{

"first_name": "Jean",

"last_name": "Peplu",

"age": 22

}

Page 34: Introduction to node.js

A bit of vocabulary…

SQL term mongoDB term

Database Database

Table Collection

Row / Entry Document

Column Field

Page 35: Introduction to node.js

Let’s install mongoDB http://www.mongodb.org/downloads

Extract the archive where you want to

Optional: add mongoDB path to your system PATH

Page 36: Introduction to node.js

Let’s install mongoDB (we’ve almost done!)

Create C:\data\db folder (or /data/db according to your OS)

Run mongoDB server via the console: use the mongod command

DO NOT CLOSE THE CONSOLE ONCEMONGODB IS LAUNCHED!

Page 37: Introduction to node.js

The communication node.js/mongoDB

We need a driver

Once again, we install it with npm!

?

Page 38: Introduction to node.js

Database

Works with database

Send data

HTML template

Asks for a template

Send HTML

Diagram of a typical case

Main server

Manages the HTTP server

The visitor

Requests

Works withSends therequested

information

Page 39: Introduction to node.js

One more tool: mongooseBecause we love to install stuff!

Page 40: Introduction to node.js

What is mongoose?

An ODM (Object Data Modeling)

Allow us to manipulate "real" objects

Current version: 3.5

Another very easy installation with npm:

http://mongoosejs.com/

Page 41: Introduction to node.js

A basic project structure

We have already created a /views folder Let’s create a /models one!

Page 42: Introduction to node.js

Let’s create our own module /models/getMongoose.js

To use it in another file:

The connection file to the database

var mongoose =require('mongoose');

mongoose.connect('localhost', 'myDatabase');

exports.mongoose = mongoose;

var mongoose = require('./models/getMongoose.js').mongoose;

Page 43: Introduction to node.js

Model construction

var mongoose = require('./getMongoose.js').mongoose,

PlayerSchema= mongoose.Schema({

first_name : String,

last_name : String,

age : Number

}),

PlayerModel = mongoose.model('Player', PlayerSchema);

exports.Player = PlayerModel;

1) Define a schema 2) Link this schema to a new model

Page 44: Introduction to node.js

Create a document

var Player = require('./models/Player.Model.js').Player,

jean = new Player({

"first_name": "Jean",

"last_name": "Peplu",

"age": 22

});

jean.save(function (error, user) {if (error) { console.log(error); }

else { console.log(Player "' + user.first_name + '"  added!'); }});

1) Get the model to use

2) Create a new instance from this model ( = a document)

3) And save it!

Page 45: Introduction to node.js

How to check everything went well Using mongoDB in the console:

Page 46: Introduction to node.js

A little more structurevar PlayerSchema= mongoose.Schema({

email : {type : String,required : true,unique : true,trim : true

},age: {

type : Number,default : 13,min :

13,max : 110

}});

List of setters for Strings:http://mongoosejs.com/docs/api.html#schema-string-js

Page 47: Introduction to node.js

Your turn!

Install mongoDB and mongoose

Modify your code from previous exercise in order to save data sent by your form

Check with your console that users are saved!

Page 48: Introduction to node.js

Retrieve data Usage of queries builders

var Player = require('./models/Player.Model.js').Player,

query = Player.find();

query.exec(function (error, players) {if (error) { console.log(error); }else {

//Do something with the list of all players}

});

Page 49: Introduction to node.js

Filter data Directly with find()

Or with where()

Using several where()

var Player = require('./models/Player.Model.js').Player,

query = Player.find({"first_name":

"Jean" });

query = Player.where('first_name', 'Jean');

query = Player.where('first_name', 'Jean') .where('age', 20);

Page 50: Introduction to node.js

Filter data: other methods Greater or equal than, lower or equal than:

Get by id:

And a lot of other methods… Read the documentation!http://mongoosejs.com/docs/api.html#model_Model.findhttp://mongoosejs.com/docs/api.html#query-js

query = Player.where('age').gte(18).lte(40);

var user_id = '5117ac79cf85d67c21000001';Player.findById(user_id, function (error, player) {

if (error) { console.log(error); }else if (!player) { console.log(‘Player not found'); }else { //Do something with the user }

});

Page 51: Introduction to node.js

Your turn!

Update your code from the previous exercise in order to match these requirements:

Home page displays all your users Below this list is a link to the register form If an error occurs while an user is being added to the

database, visitor is redirected to the form In order to know how to perform redirections, you

should read Express documentation! http://expressjs.com/api.html

Page 52: Introduction to node.js

Tables relations

Using the ObjectId type Indicate a reference model

var mongoose = require('./getMongoose.js').mongoose,

FarmSchema = mongoose.Schema({owner : {

type :mongoose.Schema.Types.ObjectId,

ref : 'Player'}

});

Page 53: Introduction to node.js

Linked documents need to be "populated" Get an owner from one of his farm:

To know more, once again… Documentation! http://mongoosejs.com/docs/populate.html

Farm.findById(farm_id)

.populate('owner') .exec(function (error, farm) {

if (error) { console.log(error); }else if (!farm) { console.log('Farm not

found'); }else {

console.log(farm.owner.first_name);}

});

Page 54: Introduction to node.js

And now, the reverse… Get a player’s farms:

Think MVC: separate Models from Controllers!

Farm.where('owner', player_id) .exec(function (error, farms) {

if (error) { console.log(error); }else {

//Do something with the list of farms

} });

Page 55: Introduction to node.js

Static methods Using the property statics from schemas

http://mongoosejs.com/docs/guide.html#statics

FarmSchema = mongoose.Schema({owner : {

type :mongoose.Schema.Types.ObjectId,

ref : 'Player'}

});

FarmSchema.statics.findByOwnerId = function (owner_id, callback) {

this.where('owner', owner_id).exec(callback);};//Call the static methodFarm.findByOwnerId('1R@nD0m!d', function (error, farm) {

//Do something});

Page 56: Introduction to node.js

Your turn!

Update your code from the previous exercise in order to manage farms:

Create a model for these farms On Home page, each username you have displayed

must now be a link to the list of farms owned by this user

Below this list is another link to a form allowing to create and add a new farm to the corresponding user

Page 57: Introduction to node.js

Database

Object Data Modeling

Interacts

Diagram of a typical case

Works with database

Send data

HTML template

Asks for a template

Send HTML

Main server

Manages the HTTP server

The visitor

Requests

Works withSends therequested

information

Page 58: Introduction to node.js

Thank you!

Do you have any questions?

[email protected]

And don’t forget: read documentations!