SlideShare uma empresa Scribd logo
1 de 32
Baixar para ler offline
Node.js, Express & MongoDB
A brief introduction
Cristina Hernández &
Alberto Irurueta
What is Node.js?
- Is an implementation of a web server based on Javascript
- Is not a web framework, it’s a platform!
(It’s like saying that .net is a web development framework)
Pros & Cons of Node.js
PROS:
- Is very very efficient in
resources usage.
- Javascript code is compiled.
- Runs on a single thread.
- WTF?
- Takes advantage of I/O locks to
handle several requests almost
concurrently on a single thread.
- Useful for I/O, not for intensive
computations
- On production systems typically
one thread is spanned per
processor
- Javascript both on
frontend & backend
- Easier for designers
CONS:
- Configuration on
Windows systems is a
pain in the ass.
- Not useful for
computation intensive
tasks or enterprise
applications.
http://blog.mixu.net/2011/02/01/understanding-
the-node-js-event-loop/
Runs on a single thread I
- All I/O call are non-blocking and event based
- Your code is the only part not running asynchronously,
hence computation intensive code (i.e. computing an
image thumbnail) blocks the whole server.
- Asynchronous code can be made using solutions similar
to WebSockets, but then thread synchronization issues
will appear.
It is typically better to run computationally intensive code in backend servers
and use an API REST or similar.
Runs on a single thread II
- But how can we attend several requests on a single
thread?
- A bit of history:
- One process per request:
- process memory is copied for each request. Too much memory usage!
- One thread per request:
- typically using POSIX accept(). Memory does not need to be copied but the OS has
additional work scheduling all the threads.
- Single asynchronous thread:
- using select() multiple requests can be attended while waiting for other I/O operations
on other requests on the same thread! Less work for the OS!
POSIX accept: http://pubs.opengroup.org/onlinepubs/009695399/functions/accept.htm
POSIX select: http://linux.die.net/man/2/selectl
Node.js event based
var result = db.query("select x from table_Y");
doSomethingWith(result); //wait for result
doSomethingWithOutResult(); //execution is blocked!!
Sync:
Async:
db.query(“select x from table_Y”, function (result) {
doSomethingWith(result); //wait for result
});
doSomethingWithOutResult(); //executes without any delay!
callback!
Node.js comparison
- Asynchronous thread handling is not exclusive of node.js!
- It is interesting for AJAX intensive applications or for
push model implementations (i.e. websockets, chats, etc)
- Other platforms have implemented this model too:
- Java: Servlet API 3.0 (December 2009)
- ASP.NET: .NET platform 4.5 (August 2012)
- PHP? Django?
Node.js installation
Mac OS X:
- Go to: https://nodejs.org/en/
- Click the big green button to download the setup
program.
Linux:
sudo apt-get update
sudo apt-get install nodejs
sudo apt-get install npm
Running & debugging
- Starting/stopping: node <file.js>
- Debugging: nodemon --debug <file.js>
- Debugger: node-inspector
Installing nodemon && node-inspector:
npm install nodemon
npm install node-inspector
Node.js - when to use it
- Chat / Messaging
- Real-Time applications
- High concurrency applications
http://stackoverflow.com/questions/5062614/how-to-decide-when-to-use-node-js
Node.js - Built-in modules
- assert
- buffer
- child_process
- cluster
- crypto
- dgram
- dns
- events
- fs
- http
- https
- net
- os
- path
- punycode
- querystring
- readline
- repl
- string_decoder
- tls
- tty
- url
- util
- vm
- zlib
Node.js - FileSystem
var fs = require("fs");
// Asynchronous read
fs.readFile('input.txt', function (err, data) {
if (err) {
return console.error(err);
}
console.log("Asynchronous read: " + data.toString());
});
// Synchronous read
var data = fs.readFileSync('input.txt');
console.log("Synchronous read: " + data.toString());
console.log("Program Ended");
What is Express?
It is a node.js based web framework
It’s the equivalent to a Servlet + web.xml in Java!
npm install --save express
Express - HTTP Server
var express = require('express');
var http = require('http');
//create express app
var app = express();
app.set('port', process.env.PORT || 3000);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
Express - Routing
app.get('/', function(request, response) {
response.send('¡Hello, Express!');
});
app.get('/users/:userName', function(request, response) {
var name = request.params.userName;
response.send('¡Hello, ' + name + '!');
});
//regex
app.get(//users/(d*)/?(edit)?/, function (request, response) {
var message = 'user number #' + request.params[0];
if (request.params[1] === 'edit') {
message = Editing ' + message;
} else {
message = 'Viewing ' + message;
}
response.send(message);
});
handler
Express - Routing POST
app.post('/users', function(request, response) {
var username = request.body.username;
response.send('¡Hello, ' + username + '!');
});
Express doesn’t parse request body by default
app.use(express.bodyParser());
middleware
Express - View rendering
app.set('views', path.join(__dirname, '..', '..', 'templates'));
app.set('view engine', 'dust');
app.get('/', function(request, response) {
response.render('index', {
title: '¡Hello, Express!',
username: 'Benítez'
});
});
view parameters
Express - NODE_ENV
Linux and OSX: export NODE_ENV=production
Windows: SET NODE_ENV=production
- Environment variable NODE_ENV
- development
- production
- By default, Express switches on view caching on
production
Express - Connect / Middlewares
function uselessMiddleware(req, res, next) { next() }
// A middleware that simply interrupts every request
function worseThanUselessMiddleware(req, res, next) {
next("Hey are you busy?")
}
- Connect is an extensible HTTP server framework for
node, providing high performance "plugins" known as
middleware.
- A middleware is simply a function with three
arguments: request, response, next
error -> request interruption
Express - Connect / Middlewares
// a middleware mounted on /user/:id; will be executed for any type of HTTP
request to /user/:id
app.use('/user/:id', function (req, res, next) {
console.log('Request Type:', req.method);
next();
})
// a middleware with no mount path; gets executed for every request to the app
app.use(function (req, res, next) {
console.log('Time:', Date.now());
next();
});
Express - Router-level middleware
var app = express();
var router = express.Router();
// shows request info for any type of HTTP request to /user/:id
router.use('/user/:id', function(req, res, next) {
console.log('Request URL:', req.originalUrl);
next();
}, function (req, res, next) {
console.log('Request Type:', req.method);
next();
});
// mount the router on the app
app.use('/', router);
Express - Error Handling
app.use(function(err, req, res, next) {
console.error(err.stack);
res.status(500).send('Something broke!');
});
- Error-handling middleware always takes four
arguments.
Express - Official middlewares
MongoDB
It’s a non relational database
It’s non-transactional: Only guarantees that read/write operations are atomic,
but rollback cannot be done
Better performance than most relational databases
Not suitable for highly concurrent applications (i.e. commerce or financial
applications where account balances or product stock must be synchronized
between requests).
Suitable to work on non-concurrent and large amounts of data (i.e. timeline,
logging, analytics, etc)
Uses Javascript as programming language!
Mongoose
Other relational & non-relational databases
MongoDB - NoSQL Database
NoSQL Database - Not Only SQL Database
Many different types:
- key-value stores
- document databases
- wide-column stores
- graph databases
MongoDB - SQL vs NoSQL
SQL Databases
- Individual records stored
as rows in tables
- Structure and data types
fixed in advance
- Transactional
- Consistent
NoSQL Databases
- Document: table-and-
row model stored in
single document
- Dynamic structure
- Atomic operations
- Not all, MongoDB is
consistent
MongoDB - setup
It’s a node package:
Start database (from cmd):
npm install mongodb
https://www.mongodb.org/
mongod //service
mongo
default port is 27017
MongoDB - structure
Database
Collection Collection Collection
Document Document
SQL
Database
Database
Table
Row
MongoDB
var Mongo = require(“mongodb”).MongoClient;
//connect to ‘test’, if not exists, create it
Mongo.connect(“mongodb://localhost:27017/test”, function(err, db){
if(!err){ //We are connected
var collection = db.collection(‘users’);
//insert into collection, if not exists, create it
collection.insert({name:’Lionel’, apellidos:’Messi’}, function(err,
collection){});
collection.update({apellidos:’Messi’}, {$set:{name:’D10S’}});
collection.remove({apellidos:’Messi’});
}
});
MongoDB
var stream = db.find({apellidos:’Messi’}).stream();
stream.on(“data”, function(item){
//fired on each result found
});
stream.on(“end”, function() {
//fired when there is no more document to look for
});
Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.

Mais conteúdo relacionado

Mais procurados

REST API and CRUD
REST API and CRUDREST API and CRUD
REST API and CRUDPrem Sanil
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsRob O'Doherty
 
Basic Concept of Node.js & NPM
Basic Concept of Node.js & NPMBasic Concept of Node.js & NPM
Basic Concept of Node.js & NPMBhargav Anadkat
 
Introduction to JSX
Introduction to JSXIntroduction to JSX
Introduction to JSXMicah Wood
 
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Edureka!
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with SpringJoshua Long
 
Angular & RXJS: examples and use cases
Angular & RXJS: examples and use casesAngular & RXJS: examples and use cases
Angular & RXJS: examples and use casesFabio Biondi
 
Build RESTful API Using Express JS
Build RESTful API Using Express JSBuild RESTful API Using Express JS
Build RESTful API Using Express JSCakra Danu Sedayu
 
Angular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP ServicesAngular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP ServicesWebStackAcademy
 

Mais procurados (20)

Nodejs presentation
Nodejs presentationNodejs presentation
Nodejs presentation
 
REST API and CRUD
REST API and CRUDREST API and CRUD
REST API and CRUD
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Basic Concept of Node.js & NPM
Basic Concept of Node.js & NPMBasic Concept of Node.js & NPM
Basic Concept of Node.js & NPM
 
Express JS
Express JSExpress JS
Express JS
 
Introduction to JSX
Introduction to JSXIntroduction to JSX
Introduction to JSX
 
Introduction to NodeJS
Introduction to NodeJSIntroduction to NodeJS
Introduction to NodeJS
 
Introduction Node.js
Introduction Node.jsIntroduction Node.js
Introduction Node.js
 
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with Spring
 
Node js
Node jsNode js
Node js
 
Reactjs
Reactjs Reactjs
Reactjs
 
Angular & RXJS: examples and use cases
Angular & RXJS: examples and use casesAngular & RXJS: examples and use cases
Angular & RXJS: examples and use cases
 
Angular 2 observables
Angular 2 observablesAngular 2 observables
Angular 2 observables
 
React workshop
React workshopReact workshop
React workshop
 
Rest API
Rest APIRest API
Rest API
 
Build RESTful API Using Express JS
Build RESTful API Using Express JSBuild RESTful API Using Express JS
Build RESTful API Using Express JS
 
Node.js Express Framework
Node.js Express FrameworkNode.js Express Framework
Node.js Express Framework
 
Node js introduction
Node js introductionNode js introduction
Node js introduction
 
Angular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP ServicesAngular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP Services
 

Destaque

All aboard the NodeJS Express
All aboard the NodeJS ExpressAll aboard the NodeJS Express
All aboard the NodeJS ExpressDavid Boyer
 
Create Rest API in Nodejs
Create Rest API in Nodejs Create Rest API in Nodejs
Create Rest API in Nodejs Irfan Maulana
 
Java script at backend nodejs
Java script at backend   nodejsJava script at backend   nodejs
Java script at backend nodejsAmit Thakkar
 
Complete MVC on NodeJS
Complete MVC on NodeJSComplete MVC on NodeJS
Complete MVC on NodeJSHüseyin BABAL
 
Nodejs Event Driven Concurrency for Web Applications
Nodejs Event Driven Concurrency for Web ApplicationsNodejs Event Driven Concurrency for Web Applications
Nodejs Event Driven Concurrency for Web ApplicationsGanesh Iyer
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsVikash Singh
 
Workshop 3: JavaScript build tools
Workshop 3: JavaScript build toolsWorkshop 3: JavaScript build tools
Workshop 3: JavaScript build toolsVisual Engineering
 
Workshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScriptWorkshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScriptVisual Engineering
 
Building your first Node app with Connect & Express
Building your first Node app with Connect & ExpressBuilding your first Node app with Connect & Express
Building your first Node app with Connect & ExpressChristian Joudrey
 
The Business Case for Node.js
The Business Case for Node.jsThe Business Case for Node.js
The Business Case for Node.jsJoe McCann
 
#7 "Многообещающий JavaScript – Promises" Денис Речкунов
#7 "Многообещающий JavaScript – Promises" Денис Речкунов#7 "Многообещающий JavaScript – Promises" Денис Речкунов
#7 "Многообещающий JavaScript – Promises" Денис РечкуновJSib
 
Why Node, Express and Postgres - presented 23 Feb 15, Talkjs, Microsoft Audit...
Why Node, Express and Postgres - presented 23 Feb 15, Talkjs, Microsoft Audit...Why Node, Express and Postgres - presented 23 Feb 15, Talkjs, Microsoft Audit...
Why Node, Express and Postgres - presented 23 Feb 15, Talkjs, Microsoft Audit...Calvin Tan
 
JavaScript as a Server side language (NodeJS): JSConf 2011, Dhaka
JavaScript as a Server side language (NodeJS): JSConf 2011, DhakaJavaScript as a Server side language (NodeJS): JSConf 2011, Dhaka
JavaScript as a Server side language (NodeJS): JSConf 2011, DhakaNurul Ferdous
 
Node.js in action
Node.js in actionNode.js in action
Node.js in actionSimon Su
 
Node.js & Twitter Bootstrap Crash Course
Node.js & Twitter Bootstrap Crash CourseNode.js & Twitter Bootstrap Crash Course
Node.js & Twitter Bootstrap Crash CourseAaron Silverman
 
How to scale and deploy NodeJS app
How to scale and deploy NodeJS appHow to scale and deploy NodeJS app
How to scale and deploy NodeJS appYacobus Reinhart
 
Nimrod: MongoDB Shell in NodeJS (JSConfUY 2015)
Nimrod: MongoDB Shell in NodeJS (JSConfUY 2015)Nimrod: MongoDB Shell in NodeJS (JSConfUY 2015)
Nimrod: MongoDB Shell in NodeJS (JSConfUY 2015)Valeri Karpov
 
Nodejs introduce - using Socket.io
Nodejs introduce - using Socket.ioNodejs introduce - using Socket.io
Nodejs introduce - using Socket.ioCaesar Chi
 

Destaque (20)

All aboard the NodeJS Express
All aboard the NodeJS ExpressAll aboard the NodeJS Express
All aboard the NodeJS Express
 
Create Rest API in Nodejs
Create Rest API in Nodejs Create Rest API in Nodejs
Create Rest API in Nodejs
 
NodeJS for Beginner
NodeJS for BeginnerNodeJS for Beginner
NodeJS for Beginner
 
Java script at backend nodejs
Java script at backend   nodejsJava script at backend   nodejs
Java script at backend nodejs
 
Complete MVC on NodeJS
Complete MVC on NodeJSComplete MVC on NodeJS
Complete MVC on NodeJS
 
Nodejs Event Driven Concurrency for Web Applications
Nodejs Event Driven Concurrency for Web ApplicationsNodejs Event Driven Concurrency for Web Applications
Nodejs Event Driven Concurrency for Web Applications
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Workshop 3: JavaScript build tools
Workshop 3: JavaScript build toolsWorkshop 3: JavaScript build tools
Workshop 3: JavaScript build tools
 
Workshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScriptWorkshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScript
 
Building your first Node app with Connect & Express
Building your first Node app with Connect & ExpressBuilding your first Node app with Connect & Express
Building your first Node app with Connect & Express
 
The Business Case for Node.js
The Business Case for Node.jsThe Business Case for Node.js
The Business Case for Node.js
 
#7 "Многообещающий JavaScript – Promises" Денис Речкунов
#7 "Многообещающий JavaScript – Promises" Денис Речкунов#7 "Многообещающий JavaScript – Promises" Денис Речкунов
#7 "Многообещающий JavaScript – Promises" Денис Речкунов
 
Why Node, Express and Postgres - presented 23 Feb 15, Talkjs, Microsoft Audit...
Why Node, Express and Postgres - presented 23 Feb 15, Talkjs, Microsoft Audit...Why Node, Express and Postgres - presented 23 Feb 15, Talkjs, Microsoft Audit...
Why Node, Express and Postgres - presented 23 Feb 15, Talkjs, Microsoft Audit...
 
NodeJS
NodeJSNodeJS
NodeJS
 
JavaScript as a Server side language (NodeJS): JSConf 2011, Dhaka
JavaScript as a Server side language (NodeJS): JSConf 2011, DhakaJavaScript as a Server side language (NodeJS): JSConf 2011, Dhaka
JavaScript as a Server side language (NodeJS): JSConf 2011, Dhaka
 
Node.js in action
Node.js in actionNode.js in action
Node.js in action
 
Node.js & Twitter Bootstrap Crash Course
Node.js & Twitter Bootstrap Crash CourseNode.js & Twitter Bootstrap Crash Course
Node.js & Twitter Bootstrap Crash Course
 
How to scale and deploy NodeJS app
How to scale and deploy NodeJS appHow to scale and deploy NodeJS app
How to scale and deploy NodeJS app
 
Nimrod: MongoDB Shell in NodeJS (JSConfUY 2015)
Nimrod: MongoDB Shell in NodeJS (JSConfUY 2015)Nimrod: MongoDB Shell in NodeJS (JSConfUY 2015)
Nimrod: MongoDB Shell in NodeJS (JSConfUY 2015)
 
Nodejs introduce - using Socket.io
Nodejs introduce - using Socket.ioNodejs introduce - using Socket.io
Nodejs introduce - using Socket.io
 

Semelhante a Workshop 4: NodeJS. Express Framework & MongoDB.

Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applicationsTom Croucher
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.pptWalaSidhom1
 
Introduction to node.js
Introduction to  node.jsIntroduction to  node.js
Introduction to node.jsMd. Sohel Rana
 
Building Web Apps with Express
Building Web Apps with ExpressBuilding Web Apps with Express
Building Web Apps with ExpressAaron Stannard
 
soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch
 
Build Web Apps using Node.js
Build Web Apps using Node.jsBuild Web Apps using Node.js
Build Web Apps using Node.jsdavidchubbs
 
Node js presentation
Node js presentationNode js presentation
Node js presentationmartincabrera
 
Server side JavaScript: going all the way
Server side JavaScript: going all the wayServer side JavaScript: going all the way
Server side JavaScript: going all the wayOleg Podsechin
 
Node.js Workshop - Sela SDP 2015
Node.js Workshop  - Sela SDP 2015Node.js Workshop  - Sela SDP 2015
Node.js Workshop - Sela SDP 2015Nir Noy
 
Node js introduction
Node js introductionNode js introduction
Node js introductionAlex Su
 
Intro to node and mongodb 1
Intro to node and mongodb   1Intro to node and mongodb   1
Intro to node and mongodb 1Mohammad Qureshi
 
Intro to node.js - Ran Mizrahi (27/8/2014)
Intro to node.js - Ran Mizrahi (27/8/2014)Intro to node.js - Ran Mizrahi (27/8/2014)
Intro to node.js - Ran Mizrahi (27/8/2014)Ran Mizrahi
 
Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)Ran Mizrahi
 
Future Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NETFuture Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NETGianluca Carucci
 
Node js
Node jsNode js
Node jshazzaz
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js frameworkBen Lin
 

Semelhante a Workshop 4: NodeJS. Express Framework & MongoDB. (20)

Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.ppt
 
Intro to Node
Intro to NodeIntro to Node
Intro to Node
 
Introduction to node.js
Introduction to  node.jsIntroduction to  node.js
Introduction to node.js
 
Building Web Apps with Express
Building Web Apps with ExpressBuilding Web Apps with Express
Building Web Apps with Express
 
soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.js
 
Build Web Apps using Node.js
Build Web Apps using Node.jsBuild Web Apps using Node.js
Build Web Apps using Node.js
 
JS everywhere 2011
JS everywhere 2011JS everywhere 2011
JS everywhere 2011
 
Node js presentation
Node js presentationNode js presentation
Node js presentation
 
Server side JavaScript: going all the way
Server side JavaScript: going all the wayServer side JavaScript: going all the way
Server side JavaScript: going all the way
 
Node.js Workshop - Sela SDP 2015
Node.js Workshop  - Sela SDP 2015Node.js Workshop  - Sela SDP 2015
Node.js Workshop - Sela SDP 2015
 
NodeJS
NodeJSNodeJS
NodeJS
 
Node js introduction
Node js introductionNode js introduction
Node js introduction
 
NodeJS
NodeJSNodeJS
NodeJS
 
Intro to node and mongodb 1
Intro to node and mongodb   1Intro to node and mongodb   1
Intro to node and mongodb 1
 
Intro to node.js - Ran Mizrahi (27/8/2014)
Intro to node.js - Ran Mizrahi (27/8/2014)Intro to node.js - Ran Mizrahi (27/8/2014)
Intro to node.js - Ran Mizrahi (27/8/2014)
 
Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)
 
Future Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NETFuture Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NET
 
Node js
Node jsNode js
Node js
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js framework
 

Mais de Visual Engineering

Workshop 27: Isomorphic web apps with ReactJS
Workshop 27: Isomorphic web apps with ReactJSWorkshop 27: Isomorphic web apps with ReactJS
Workshop 27: Isomorphic web apps with ReactJSVisual Engineering
 
Workshop iOS 4: Closures, generics & operators
Workshop iOS 4: Closures, generics & operatorsWorkshop iOS 4: Closures, generics & operators
Workshop iOS 4: Closures, generics & operatorsVisual Engineering
 
Workshop iOS 3: Testing, protocolos y extensiones
Workshop iOS 3: Testing, protocolos y extensionesWorkshop iOS 3: Testing, protocolos y extensiones
Workshop iOS 3: Testing, protocolos y extensionesVisual Engineering
 
Workshop iOS 2: Swift - Structures
Workshop iOS 2: Swift - StructuresWorkshop iOS 2: Swift - Structures
Workshop iOS 2: Swift - StructuresVisual Engineering
 
Workhop iOS 1: Fundamentos de Swift
Workhop iOS 1: Fundamentos de SwiftWorkhop iOS 1: Fundamentos de Swift
Workhop iOS 1: Fundamentos de SwiftVisual Engineering
 
Workshop 26: React Native - The Native Side
Workshop 26: React Native - The Native SideWorkshop 26: React Native - The Native Side
Workshop 26: React Native - The Native SideVisual Engineering
 
Workshop 25: React Native - Components
Workshop 25: React Native - ComponentsWorkshop 25: React Native - Components
Workshop 25: React Native - ComponentsVisual Engineering
 
Workshop 24: React Native Introduction
Workshop 24: React Native IntroductionWorkshop 24: React Native Introduction
Workshop 24: React Native IntroductionVisual Engineering
 
Workshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingVisual Engineering
 
Workshop 22: ReactJS Redux Advanced
Workshop 22: ReactJS Redux AdvancedWorkshop 22: ReactJS Redux Advanced
Workshop 22: ReactJS Redux AdvancedVisual Engineering
 
Workshop 22: React-Redux Middleware
Workshop 22: React-Redux MiddlewareWorkshop 22: React-Redux Middleware
Workshop 22: React-Redux MiddlewareVisual Engineering
 
Workshop 20: ReactJS Part II Flux Pattern & Redux
Workshop 20: ReactJS Part II Flux Pattern & ReduxWorkshop 20: ReactJS Part II Flux Pattern & Redux
Workshop 20: ReactJS Part II Flux Pattern & ReduxVisual Engineering
 
Workshop 19: ReactJS Introduction
Workshop 19: ReactJS IntroductionWorkshop 19: ReactJS Introduction
Workshop 19: ReactJS IntroductionVisual Engineering
 
Workshop 18: CSS Animations & cool effects
Workshop 18: CSS Animations & cool effectsWorkshop 18: CSS Animations & cool effects
Workshop 18: CSS Animations & cool effectsVisual Engineering
 
Workshop 14: AngularJS Parte III
Workshop 14: AngularJS Parte IIIWorkshop 14: AngularJS Parte III
Workshop 14: AngularJS Parte IIIVisual Engineering
 
Workshop 13: AngularJS Parte II
Workshop 13: AngularJS Parte IIWorkshop 13: AngularJS Parte II
Workshop 13: AngularJS Parte IIVisual Engineering
 

Mais de Visual Engineering (20)

Workshop 27: Isomorphic web apps with ReactJS
Workshop 27: Isomorphic web apps with ReactJSWorkshop 27: Isomorphic web apps with ReactJS
Workshop 27: Isomorphic web apps with ReactJS
 
Workshop iOS 4: Closures, generics & operators
Workshop iOS 4: Closures, generics & operatorsWorkshop iOS 4: Closures, generics & operators
Workshop iOS 4: Closures, generics & operators
 
Workshop iOS 3: Testing, protocolos y extensiones
Workshop iOS 3: Testing, protocolos y extensionesWorkshop iOS 3: Testing, protocolos y extensiones
Workshop iOS 3: Testing, protocolos y extensiones
 
Workshop iOS 2: Swift - Structures
Workshop iOS 2: Swift - StructuresWorkshop iOS 2: Swift - Structures
Workshop iOS 2: Swift - Structures
 
Workhop iOS 1: Fundamentos de Swift
Workhop iOS 1: Fundamentos de SwiftWorkhop iOS 1: Fundamentos de Swift
Workhop iOS 1: Fundamentos de Swift
 
Workshop 26: React Native - The Native Side
Workshop 26: React Native - The Native SideWorkshop 26: React Native - The Native Side
Workshop 26: React Native - The Native Side
 
Workshop 25: React Native - Components
Workshop 25: React Native - ComponentsWorkshop 25: React Native - Components
Workshop 25: React Native - Components
 
Workshop 24: React Native Introduction
Workshop 24: React Native IntroductionWorkshop 24: React Native Introduction
Workshop 24: React Native Introduction
 
Workshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testing
 
Workshop 22: ReactJS Redux Advanced
Workshop 22: ReactJS Redux AdvancedWorkshop 22: ReactJS Redux Advanced
Workshop 22: ReactJS Redux Advanced
 
Workshop 22: React-Redux Middleware
Workshop 22: React-Redux MiddlewareWorkshop 22: React-Redux Middleware
Workshop 22: React-Redux Middleware
 
Workshop 21: React Router
Workshop 21: React RouterWorkshop 21: React Router
Workshop 21: React Router
 
Workshop 20: ReactJS Part II Flux Pattern & Redux
Workshop 20: ReactJS Part II Flux Pattern & ReduxWorkshop 20: ReactJS Part II Flux Pattern & Redux
Workshop 20: ReactJS Part II Flux Pattern & Redux
 
Workshop 19: ReactJS Introduction
Workshop 19: ReactJS IntroductionWorkshop 19: ReactJS Introduction
Workshop 19: ReactJS Introduction
 
Workshop 18: CSS Animations & cool effects
Workshop 18: CSS Animations & cool effectsWorkshop 18: CSS Animations & cool effects
Workshop 18: CSS Animations & cool effects
 
Workshop 17: EmberJS parte II
Workshop 17: EmberJS parte IIWorkshop 17: EmberJS parte II
Workshop 17: EmberJS parte II
 
Workshop 16: EmberJS Parte I
Workshop 16: EmberJS Parte IWorkshop 16: EmberJS Parte I
Workshop 16: EmberJS Parte I
 
Workshop 15: Ionic framework
Workshop 15: Ionic frameworkWorkshop 15: Ionic framework
Workshop 15: Ionic framework
 
Workshop 14: AngularJS Parte III
Workshop 14: AngularJS Parte IIIWorkshop 14: AngularJS Parte III
Workshop 14: AngularJS Parte III
 
Workshop 13: AngularJS Parte II
Workshop 13: AngularJS Parte IIWorkshop 13: AngularJS Parte II
Workshop 13: AngularJS Parte II
 

Último

Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf31events.com
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Developmentvyaparkranti
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identityteam-WIBU
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 

Último (20)

Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Development
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identity
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 

Workshop 4: NodeJS. Express Framework & MongoDB.

  • 1. Node.js, Express & MongoDB A brief introduction Cristina Hernández & Alberto Irurueta
  • 2. What is Node.js? - Is an implementation of a web server based on Javascript - Is not a web framework, it’s a platform! (It’s like saying that .net is a web development framework)
  • 3. Pros & Cons of Node.js PROS: - Is very very efficient in resources usage. - Javascript code is compiled. - Runs on a single thread. - WTF? - Takes advantage of I/O locks to handle several requests almost concurrently on a single thread. - Useful for I/O, not for intensive computations - On production systems typically one thread is spanned per processor - Javascript both on frontend & backend - Easier for designers CONS: - Configuration on Windows systems is a pain in the ass. - Not useful for computation intensive tasks or enterprise applications. http://blog.mixu.net/2011/02/01/understanding- the-node-js-event-loop/
  • 4. Runs on a single thread I - All I/O call are non-blocking and event based - Your code is the only part not running asynchronously, hence computation intensive code (i.e. computing an image thumbnail) blocks the whole server. - Asynchronous code can be made using solutions similar to WebSockets, but then thread synchronization issues will appear. It is typically better to run computationally intensive code in backend servers and use an API REST or similar.
  • 5. Runs on a single thread II - But how can we attend several requests on a single thread? - A bit of history: - One process per request: - process memory is copied for each request. Too much memory usage! - One thread per request: - typically using POSIX accept(). Memory does not need to be copied but the OS has additional work scheduling all the threads. - Single asynchronous thread: - using select() multiple requests can be attended while waiting for other I/O operations on other requests on the same thread! Less work for the OS! POSIX accept: http://pubs.opengroup.org/onlinepubs/009695399/functions/accept.htm POSIX select: http://linux.die.net/man/2/selectl
  • 6. Node.js event based var result = db.query("select x from table_Y"); doSomethingWith(result); //wait for result doSomethingWithOutResult(); //execution is blocked!! Sync: Async: db.query(“select x from table_Y”, function (result) { doSomethingWith(result); //wait for result }); doSomethingWithOutResult(); //executes without any delay! callback!
  • 7. Node.js comparison - Asynchronous thread handling is not exclusive of node.js! - It is interesting for AJAX intensive applications or for push model implementations (i.e. websockets, chats, etc) - Other platforms have implemented this model too: - Java: Servlet API 3.0 (December 2009) - ASP.NET: .NET platform 4.5 (August 2012) - PHP? Django?
  • 8. Node.js installation Mac OS X: - Go to: https://nodejs.org/en/ - Click the big green button to download the setup program. Linux: sudo apt-get update sudo apt-get install nodejs sudo apt-get install npm
  • 9. Running & debugging - Starting/stopping: node <file.js> - Debugging: nodemon --debug <file.js> - Debugger: node-inspector Installing nodemon && node-inspector: npm install nodemon npm install node-inspector
  • 10. Node.js - when to use it - Chat / Messaging - Real-Time applications - High concurrency applications http://stackoverflow.com/questions/5062614/how-to-decide-when-to-use-node-js
  • 11. Node.js - Built-in modules - assert - buffer - child_process - cluster - crypto - dgram - dns - events - fs - http - https - net - os - path - punycode - querystring - readline - repl - string_decoder - tls - tty - url - util - vm - zlib
  • 12. Node.js - FileSystem var fs = require("fs"); // Asynchronous read fs.readFile('input.txt', function (err, data) { if (err) { return console.error(err); } console.log("Asynchronous read: " + data.toString()); }); // Synchronous read var data = fs.readFileSync('input.txt'); console.log("Synchronous read: " + data.toString()); console.log("Program Ended");
  • 13. What is Express? It is a node.js based web framework It’s the equivalent to a Servlet + web.xml in Java! npm install --save express
  • 14. Express - HTTP Server var express = require('express'); var http = require('http'); //create express app var app = express(); app.set('port', process.env.PORT || 3000); http.createServer(app).listen(app.get('port'), function(){ console.log('Express server listening on port ' + app.get('port')); });
  • 15. Express - Routing app.get('/', function(request, response) { response.send('¡Hello, Express!'); }); app.get('/users/:userName', function(request, response) { var name = request.params.userName; response.send('¡Hello, ' + name + '!'); }); //regex app.get(//users/(d*)/?(edit)?/, function (request, response) { var message = 'user number #' + request.params[0]; if (request.params[1] === 'edit') { message = Editing ' + message; } else { message = 'Viewing ' + message; } response.send(message); }); handler
  • 16. Express - Routing POST app.post('/users', function(request, response) { var username = request.body.username; response.send('¡Hello, ' + username + '!'); }); Express doesn’t parse request body by default app.use(express.bodyParser()); middleware
  • 17. Express - View rendering app.set('views', path.join(__dirname, '..', '..', 'templates')); app.set('view engine', 'dust'); app.get('/', function(request, response) { response.render('index', { title: '¡Hello, Express!', username: 'Benítez' }); }); view parameters
  • 18. Express - NODE_ENV Linux and OSX: export NODE_ENV=production Windows: SET NODE_ENV=production - Environment variable NODE_ENV - development - production - By default, Express switches on view caching on production
  • 19. Express - Connect / Middlewares function uselessMiddleware(req, res, next) { next() } // A middleware that simply interrupts every request function worseThanUselessMiddleware(req, res, next) { next("Hey are you busy?") } - Connect is an extensible HTTP server framework for node, providing high performance "plugins" known as middleware. - A middleware is simply a function with three arguments: request, response, next error -> request interruption
  • 20. Express - Connect / Middlewares // a middleware mounted on /user/:id; will be executed for any type of HTTP request to /user/:id app.use('/user/:id', function (req, res, next) { console.log('Request Type:', req.method); next(); }) // a middleware with no mount path; gets executed for every request to the app app.use(function (req, res, next) { console.log('Time:', Date.now()); next(); });
  • 21. Express - Router-level middleware var app = express(); var router = express.Router(); // shows request info for any type of HTTP request to /user/:id router.use('/user/:id', function(req, res, next) { console.log('Request URL:', req.originalUrl); next(); }, function (req, res, next) { console.log('Request Type:', req.method); next(); }); // mount the router on the app app.use('/', router);
  • 22. Express - Error Handling app.use(function(err, req, res, next) { console.error(err.stack); res.status(500).send('Something broke!'); }); - Error-handling middleware always takes four arguments.
  • 23. Express - Official middlewares
  • 24. MongoDB It’s a non relational database It’s non-transactional: Only guarantees that read/write operations are atomic, but rollback cannot be done Better performance than most relational databases Not suitable for highly concurrent applications (i.e. commerce or financial applications where account balances or product stock must be synchronized between requests). Suitable to work on non-concurrent and large amounts of data (i.e. timeline, logging, analytics, etc) Uses Javascript as programming language! Mongoose Other relational & non-relational databases
  • 25. MongoDB - NoSQL Database NoSQL Database - Not Only SQL Database Many different types: - key-value stores - document databases - wide-column stores - graph databases
  • 26. MongoDB - SQL vs NoSQL SQL Databases - Individual records stored as rows in tables - Structure and data types fixed in advance - Transactional - Consistent NoSQL Databases - Document: table-and- row model stored in single document - Dynamic structure - Atomic operations - Not all, MongoDB is consistent
  • 27. MongoDB - setup It’s a node package: Start database (from cmd): npm install mongodb https://www.mongodb.org/ mongod //service mongo default port is 27017
  • 28. MongoDB - structure Database Collection Collection Collection Document Document SQL Database Database Table Row
  • 29. MongoDB var Mongo = require(“mongodb”).MongoClient; //connect to ‘test’, if not exists, create it Mongo.connect(“mongodb://localhost:27017/test”, function(err, db){ if(!err){ //We are connected var collection = db.collection(‘users’); //insert into collection, if not exists, create it collection.insert({name:’Lionel’, apellidos:’Messi’}, function(err, collection){}); collection.update({apellidos:’Messi’}, {$set:{name:’D10S’}}); collection.remove({apellidos:’Messi’}); } });
  • 30. MongoDB var stream = db.find({apellidos:’Messi’}).stream(); stream.on(“data”, function(item){ //fired on each result found }); stream.on(“end”, function() { //fired when there is no more document to look for });