SlideShare a Scribd company logo
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.

More Related Content

PPTX
Google Vertex AI
PDF
Nodejs presentation
PDF
PowerBI Training
PPT
Angular 8
PPTX
Introduction to Node.js
PPTX
Introduction to Node.js
PDF
Konsep dan Studi Kebijakan Publik
PDF
Test Environment Management
Google Vertex AI
Nodejs presentation
PowerBI Training
Angular 8
Introduction to Node.js
Introduction to Node.js
Konsep dan Studi Kebijakan Publik
Test Environment Management

What's hot (20)

PPT
Node js Modules and Event Emitters
PDF
What is Node.js | Node.js Tutorial for Beginners | Node.js Modules | Node.js ...
PPTX
Node.js Express
PPTX
Node js introduction
PPTX
Node js Introduction
PDF
NodeJS for Beginner
PPTX
Introduction to spring boot
PDF
Why Vue.js?
PPTX
What Is Express JS?
PPTX
Basic Concept of Node.js & NPM
PDF
Introduction to Node.js
PPTX
Presentation on "An Introduction to ReactJS"
PDF
Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js + Expres...
PPTX
PPTX
Express js
PDF
Node JS Crash Course
PPTX
React-JS.pptx
PPTX
Build RESTful API Using Express JS
PPTX
Introduction Node.js
PPTX
Mern stack developement
Node js Modules and Event Emitters
What is Node.js | Node.js Tutorial for Beginners | Node.js Modules | Node.js ...
Node.js Express
Node js introduction
Node js Introduction
NodeJS for Beginner
Introduction to spring boot
Why Vue.js?
What Is Express JS?
Basic Concept of Node.js & NPM
Introduction to Node.js
Presentation on "An Introduction to ReactJS"
Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js + Expres...
Express js
Node JS Crash Course
React-JS.pptx
Build RESTful API Using Express JS
Introduction Node.js
Mern stack developement
Ad

Viewers also liked (20)

PDF
All aboard the NodeJS Express
PPTX
Create Rest API in Nodejs
PPTX
Java script at backend nodejs
PDF
Complete MVC on NodeJS
PPT
Nodejs Event Driven Concurrency for Web Applications
PDF
Express node js
PDF
Workshop 3: JavaScript build tools
PPTX
Workshop 1: Good practices in JavaScript
PPT
Building your first Node app with Connect & Express
PPT
The Business Case for Node.js
PDF
#7 "Многообещающий JavaScript – Promises" Денис Речкунов
PPTX
Why Node, Express and Postgres - presented 23 Feb 15, Talkjs, Microsoft Audit...
KEY
NodeJS
PDF
JavaScript as a Server side language (NodeJS): JSConf 2011, Dhaka
PDF
Node.js in action
PDF
Node.js & Twitter Bootstrap Crash Course
PPT
How to scale and deploy NodeJS app
PDF
Nimrod: MongoDB Shell in NodeJS (JSConfUY 2015)
PPTX
Nodejs introduce - using Socket.io
PDF
Burgas Conf 21.06.2014 - Single page application Angularjs and Nodejs
All aboard the NodeJS Express
Create Rest API in Nodejs
Java script at backend nodejs
Complete MVC on NodeJS
Nodejs Event Driven Concurrency for Web Applications
Express node js
Workshop 3: JavaScript build tools
Workshop 1: Good practices in JavaScript
Building your first Node app with Connect & Express
The Business Case for Node.js
#7 "Многообещающий JavaScript – Promises" Денис Речкунов
Why Node, Express and Postgres - presented 23 Feb 15, Talkjs, Microsoft Audit...
NodeJS
JavaScript as a Server side language (NodeJS): JSConf 2011, Dhaka
Node.js in action
Node.js & Twitter Bootstrap Crash Course
How to scale and deploy NodeJS app
Nimrod: MongoDB Shell in NodeJS (JSConfUY 2015)
Nodejs introduce - using Socket.io
Burgas Conf 21.06.2014 - Single page application Angularjs and Nodejs
Ad

Similar to Workshop 4: NodeJS. Express Framework & MongoDB. (20)

KEY
Writing robust Node.js applications
PPT
nodejs_at_a_glance.ppt
PPT
nodejs_at_a_glance, understanding java script
PPTX
Intro to Node
PPTX
Introduction to node.js
PPTX
Building Web Apps with Express
PDF
soft-shake.ch - Hands on Node.js
PDF
Build Web Apps using Node.js
PPT
JS everywhere 2011
PPT
Node js presentation
PPT
Server side JavaScript: going all the way
PPTX
Node.js Workshop - Sela SDP 2015
PPTX
NodeJS
PDF
Node js introduction
PDF
NodeJS
PPTX
Intro to node and mongodb 1
PDF
Intro to node.js - Ran Mizrahi (28/8/14)
PDF
Intro to node.js - Ran Mizrahi (27/8/2014)
PDF
Future Decoded - Node.js per sviluppatori .NET
ODP
Node js
Writing robust Node.js applications
nodejs_at_a_glance.ppt
nodejs_at_a_glance, understanding java script
Intro to Node
Introduction to node.js
Building Web Apps with Express
soft-shake.ch - Hands on Node.js
Build Web Apps using Node.js
JS everywhere 2011
Node js presentation
Server side JavaScript: going all the way
Node.js Workshop - Sela SDP 2015
NodeJS
Node js introduction
NodeJS
Intro to node and mongodb 1
Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (27/8/2014)
Future Decoded - Node.js per sviluppatori .NET
Node js

More from Visual Engineering (20)

PDF
Workshop 27: Isomorphic web apps with ReactJS
PDF
Workshop iOS 4: Closures, generics & operators
PDF
Workshop iOS 3: Testing, protocolos y extensiones
PDF
Workshop iOS 2: Swift - Structures
PDF
Workhop iOS 1: Fundamentos de Swift
PDF
Workshop 26: React Native - The Native Side
PDF
Workshop 25: React Native - Components
PDF
Workshop 24: React Native Introduction
PDF
Workshop 23: ReactJS, React & Redux testing
PDF
Workshop 22: ReactJS Redux Advanced
PDF
Workshop 22: React-Redux Middleware
PDF
Workshop 21: React Router
PDF
Workshop 20: ReactJS Part II Flux Pattern & Redux
PDF
Workshop 19: ReactJS Introduction
PDF
Workshop 18: CSS Animations & cool effects
PDF
Workshop 17: EmberJS parte II
PDF
Workshop 16: EmberJS Parte I
PDF
Workshop 15: Ionic framework
PDF
Workshop 14: AngularJS Parte III
PDF
Workshop 13: AngularJS Parte II
Workshop 27: Isomorphic web apps with ReactJS
Workshop iOS 4: Closures, generics & operators
Workshop iOS 3: Testing, protocolos y extensiones
Workshop iOS 2: Swift - Structures
Workhop iOS 1: Fundamentos de Swift
Workshop 26: React Native - The Native Side
Workshop 25: React Native - Components
Workshop 24: React Native Introduction
Workshop 23: ReactJS, React & Redux testing
Workshop 22: ReactJS Redux Advanced
Workshop 22: React-Redux Middleware
Workshop 21: React Router
Workshop 20: ReactJS Part II Flux Pattern & Redux
Workshop 19: ReactJS Introduction
Workshop 18: CSS Animations & cool effects
Workshop 17: EmberJS parte II
Workshop 16: EmberJS Parte I
Workshop 15: Ionic framework
Workshop 14: AngularJS Parte III
Workshop 13: AngularJS Parte II

Recently uploaded (20)

PDF
PTS Company Brochure 2025 (1).pdf.......
PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PDF
AI in Product Development-omnex systems
PPTX
Odoo POS Development Services by CandidRoot Solutions
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PPTX
AIRLINE PRICE API | FLIGHT API COST |
PDF
top salesforce developer skills in 2025.pdf
PDF
Softaken Excel to vCard Converter Software.pdf
PDF
Understanding Forklifts - TECH EHS Solution
PDF
How Creative Agencies Leverage Project Management Software.pdf
PDF
Multi-factor Authentication (MFA) requirement for Microsoft 365 Admin Center_...
PPTX
What to Capture When It Breaks: 16 Artifacts That Reveal Root Causes
DOCX
The Five Best AI Cover Tools in 2025.docx
PPTX
ISO 45001 Occupational Health and Safety Management System
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PDF
Digital Strategies for Manufacturing Companies
PDF
medical staffing services at VALiNTRY
PPTX
Presentation of Computer CLASS 2 .pptx
PTS Company Brochure 2025 (1).pdf.......
VVF-Customer-Presentation2025-Ver1.9.pptx
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
AI in Product Development-omnex systems
Odoo POS Development Services by CandidRoot Solutions
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
How to Migrate SBCGlobal Email to Yahoo Easily
AIRLINE PRICE API | FLIGHT API COST |
top salesforce developer skills in 2025.pdf
Softaken Excel to vCard Converter Software.pdf
Understanding Forklifts - TECH EHS Solution
How Creative Agencies Leverage Project Management Software.pdf
Multi-factor Authentication (MFA) requirement for Microsoft 365 Admin Center_...
What to Capture When It Breaks: 16 Artifacts That Reveal Root Causes
The Five Best AI Cover Tools in 2025.docx
ISO 45001 Occupational Health and Safety Management System
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
Digital Strategies for Manufacturing Companies
medical staffing services at VALiNTRY
Presentation of Computer CLASS 2 .pptx

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 });