SlideShare a Scribd company logo
1 of 56
Download to read offline
TECHBAR
Nodejs + MongoDB + Mongoose
Me (www.massimobiagioli.it)
biagiolimassimo@gmail.com
massimo.biagioli
maxbiag80
+MassimoBiagioli
massimo-biagioli/28/8b0/94
massimobiagioli
Stack
+ +
Nodejs
http://nodejs.org/
Nodejs
Framework che permette di usare V8,
l'interprete JavaScript di Google anche per
realizzare web application e applicazioni
fortemente orientate al networking.
(fonte: html.it)
Nodejs
Un primo esempio
Clonare questo progetto da GitHub:
https://github.com/massimobiagioli/techbar-node
Esaminare il file:
techbar-getting-started-01.js
Nodejs
Express (http://expressjs.com/)
npm install express --save
- Framework per la creazione di Web Application
- Utilizzato per la realizzazione di API RESTful
- Meccanismo d routing
- Configurabile tramite middlewares
Nodejs
Middlewares
body-parser (https://github.com/expressjs/body-parser)
npm install body-parser --save
morgan (https://github.com/expressjs/morgan)
npm install morgan --save
Nodejs
Dichiarazione variabili
var express = require('express'),
bodyParser = require('body-parser'),
http = require('http'),
morgan = require('morgan'),
app = express(),
router = express.Router();
Nodejs
Configurazione app
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(morgan('combined'));
Nodejs
Configurazione routes
router.get('/handshake', function(req, res) {
res.json({ message: 'handshake ok' });
});
app.use('/api', router);
Nodejs
Creazione server
http.createServer(app).listen(3000, 'localhost', function() {
console.log("Express server listening on port " + 3000);
});
Nodejs
Collegandosi dal browser a questo indirizzo:
http://localhost:3000/api/handshake
Avremo la seguente risposta:
{"message":"handshake ok"}
Nodejs
Creare un middleware
Esaminare il file:
techbar-getting-started-02.js
Nodejs
Definizione
var printUserAgent = function(req, res, next) {
var userAgent = req.headers['user-agent'];
if (userAgent.indexOf('Mozilla') > -1) {
console.log('Dovresti usare IE!!!');
}
next();
};
Nodejs
Utilizzo
app.use(printUserAgent);
Nodejs
Router
Elementi di una route:
- Verb
- Url
- Callback
Nodejs
Router >> Verb
- GET
- POST
- PUT
- DELETE
Nodejs
Router >> Url
- /api/hello
- /api/hello/:name
- /api/hello/:name(regex)
Nodejs
Router >> Callback
function(req, res) {
res.json({ message: 'hello ' + req.params.name });
}
Nodejs
CommonJs
http://wiki.commonjs.org/wiki/CommonJS
Esaminare il file:
techbar-getting-started-03.js
Nodejs
Definizione del modulo “example”
var sum = function(a, b) {
return a + b;
};
module.exports = {
sum: sum
};
Nodejs
Utilizzo del modulo “example”
var example = require('./lib/example');
console.log("Result: " + example.sum(3, 4));
Nodejs
npmjs
https://www.npmjs.com/
Nodejs
Dipendenze: il file “package.json”
…
"dependencies": {
"mongoose": "~3.8.21",
"express": "~4.11.1",
"http": "0.0.0",
"cors": "~2.5.3",
"body-parser": "~1.10.2",
"morgan": "~1.5.1"
}
...
npm install
Nodejs
Le insidie...
Nodejs
Insidie >> La Piramide di Doom
Esempio:
techbar-getting-started-04.js
Soluzione:
techbar-getting-started-05.js
q
Nodejs
Insidie >> JavaScript Bad Parts
MongoDB
http://www.mongodb.org/
MongoDB
MongoDB è un database NoSQL di tipo
document: questo vuol dire che è
particolarmente orientato ad un approccio alla
modellazione di tipo domain driven e ad un
utilizzo “ad oggetti” delle entità.
(fonte: html.it)
MongoDB
Non esiste il concetto di “Tabella” (elemento
chiave dei RDBMS).
Esiste invece quello di “Collection”.
MongoDB
https://mongolab.com free plan
MongoDB
UMongo
http://edgytech.com/umongo/
MongoDB
UMongo >> Parametri di connessione
Mongoose
http://mongoosejs.com/
Mongoose
E’ un modulo che consente di interfacciare
NodeJs con MongoDb.
Si basa sul concetto di “Schema” per la
rappresentazione delle collection di MongoDb.
Mongoose
Oltre alle classiche operazioni “CRUD”,
consente anche di effettuare la validazione dei
modelli, in funzione delle regole definite nello
Schema.
Mongoose
Connessione a MongoDb
Esempio:
techbar-mongoose-connection.js
Mongoose
var express = require('express'),
bodyParser = require('body-parser'),
http = require('http'),
morgan = require('morgan'),
mongoose = require('mongoose'),
app = express(),
db;
Mongoose
mongoose.connect('mongodb://techbar:techbar@ds031601.mongolab.com:31601/techbar');
db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error: '));
db.once('open', function() {
console.log("Connected to MongoDb");
http.createServer(app).listen(3000, 'localhost', function() {
console.log("Express server listening on port " + 3000);
});
});
Mongoose
Schema: definizione della struttura della collection
var EventSchema = new mongoose.Schema({
title: {type: String, required: true},
speaker: {type: String, required: true},
where: {type: String, required: true},
….
}, {
collection: 'events'
});
Mongoose
Model: definizione oggeto basato su uno schema
var Event = mongoose.model('Event', EventSchema)
Attraverso il model è possibile eseguire le classiche operazioni “CRUD” sulla
collection (vedi documentazione mongoose model).
Nell’esempio, la definizione di schemi e modelli sono nel modulo “Models”, che
utilizza mongoose come dipendenza.
Mongoose
Popolamento collection “events”
Il file “techbar-initdb.js” mostra un esempio di popolamento della collection
“events”.
Viene chiamato il metodo “save” (in questo caso senza callback).
Mongoose
Esempio completo
Nel file “server.js” vengono mostrati i seguenti aspetti:
- Creazione di un server http
- Definizione di routes
- Definizone del modulo “Routes” (CRUD)
- Pagina di test (html + js)
Mongoose
Esempio completo >> Routes
var
...
Models = require('./lib/Models'),
models = Models.create(mongoose),
Routes = require('./lib/Routes'),
routes = Routes.create(models);
Mongoose
Esempio completo >> Routes
router.get('/list', routes.list);
…
….
app.use('/api', router);
http://localhost:3000/api/list
Mongoose
Ricerca
models.Event.find(conditions, function(err, result) {
handleResponse(response, err, result);
});
Mongoose
Conditions
Mongoose
Conditions
Mongoose
Inserimento
event = new models.Event(data);
event.save(function(err, result) {
handleResponse(response, err, result);
});
Mongoose
Cancellazione
models.Event.findOne({ "_id": eventId }, function(err, doc) {
if (!err) {
doc.remove(function(errRemove) {
handleResponse(response, errRemove, eventId);
});
} else {
handleResponse(response, true, 'not found!');
}
});
Mongoose
Map-Reduce
http://docs.mongodb.org/manual/core/map-reduce/
Map-reduce is a data processing paradigm for condensing
large volumes of data into useful aggregated results.
Mongoose
Map-Reduce
Mongoose
Map-Reduce
Mongoose
Map-Reduce
var o = {};
o.scope = {
...
};
o.map = function() {
...
};
o.reduce = function(key, values) {
...
};
models.Event.mapReduce(o, function(err, results, stats) {
...
});
Ringraziamenti

More Related Content

Similar to Techbar nodejs+mongodb+mongoose

MongoDb and Scala SpringFramework Meeting
MongoDb and Scala SpringFramework MeetingMongoDb and Scala SpringFramework Meeting
MongoDb and Scala SpringFramework Meetingguest67beeb9
 
Sviluppo Web Agile con Castle Monorail
Sviluppo Web Agile con Castle MonorailSviluppo Web Agile con Castle Monorail
Sviluppo Web Agile con Castle MonorailDotNetMarche
 
MongoDB SpringFramework Meeting september 2009
MongoDB SpringFramework Meeting september 2009MongoDB SpringFramework Meeting september 2009
MongoDB SpringFramework Meeting september 2009Massimiliano Dessì
 
Rich client application: MVC4 + MVVM = Knockout.js
Rich client application: MVC4 + MVVM = Knockout.jsRich client application: MVC4 + MVVM = Knockout.js
Rich client application: MVC4 + MVVM = Knockout.jsGiorgio Di Nardo
 
Migliora il tuo codice con knockout.js
Migliora il tuo codice con knockout.jsMigliora il tuo codice con knockout.js
Migliora il tuo codice con knockout.jsAndrea Dottor
 
Web base - Javascript (Node.js): Elementi di base
Web base - Javascript (Node.js): Elementi di baseWeb base - Javascript (Node.js): Elementi di base
Web base - Javascript (Node.js): Elementi di baseAnnalisa Vignoli
 
Web base-03-js-numeri stringearray
Web base-03-js-numeri stringearrayWeb base-03-js-numeri stringearray
Web base-03-js-numeri stringearrayStudiabo
 
Hands on MVC - Mastering the Web
Hands on MVC - Mastering the WebHands on MVC - Mastering the Web
Hands on MVC - Mastering the WebClaudio Gandelli
 
Talk introduzioneaspnetcore
Talk introduzioneaspnetcoreTalk introduzioneaspnetcore
Talk introduzioneaspnetcoreMauro Di Liddo
 
Blazor: are we ready for the launch?
Blazor: are we ready for the launch?Blazor: are we ready for the launch?
Blazor: are we ready for the launch?Andrea Agnoletto
 
Sviluppo web con Ruby on Rails
Sviluppo web con Ruby on RailsSviluppo web con Ruby on Rails
Sviluppo web con Ruby on Railsjekil
 
ASP.NET MVC 6 - uno sguardo al futuro
ASP.NET MVC 6 - uno sguardo al futuroASP.NET MVC 6 - uno sguardo al futuro
ASP.NET MVC 6 - uno sguardo al futuroAndrea Dottor
 
node.js e Postgresql
node.js e Postgresqlnode.js e Postgresql
node.js e PostgresqlLucio Grenzi
 
2014.04.04 Sviluppare applicazioni web (completamente) on line con Visual Stu...
2014.04.04 Sviluppare applicazioni web (completamente) on line con Visual Stu...2014.04.04 Sviluppare applicazioni web (completamente) on line con Visual Stu...
2014.04.04 Sviluppare applicazioni web (completamente) on line con Visual Stu...Marco Parenzan
 
Javascript task automation
Javascript task automationJavascript task automation
Javascript task automationDotNetCampus
 

Similar to Techbar nodejs+mongodb+mongoose (20)

MongoDb and Scala SpringFramework Meeting
MongoDb and Scala SpringFramework MeetingMongoDb and Scala SpringFramework Meeting
MongoDb and Scala SpringFramework Meeting
 
Sviluppo Web Agile con Castle Monorail
Sviluppo Web Agile con Castle MonorailSviluppo Web Agile con Castle Monorail
Sviluppo Web Agile con Castle Monorail
 
MongoDB SpringFramework Meeting september 2009
MongoDB SpringFramework Meeting september 2009MongoDB SpringFramework Meeting september 2009
MongoDB SpringFramework Meeting september 2009
 
Rich client application: MVC4 + MVVM = Knockout.js
Rich client application: MVC4 + MVVM = Knockout.jsRich client application: MVC4 + MVVM = Knockout.js
Rich client application: MVC4 + MVVM = Knockout.js
 
Migliora il tuo codice con knockout.js
Migliora il tuo codice con knockout.jsMigliora il tuo codice con knockout.js
Migliora il tuo codice con knockout.js
 
Web base - Javascript (Node.js): Elementi di base
Web base - Javascript (Node.js): Elementi di baseWeb base - Javascript (Node.js): Elementi di base
Web base - Javascript (Node.js): Elementi di base
 
Web base-03-js-numeri stringearray
Web base-03-js-numeri stringearrayWeb base-03-js-numeri stringearray
Web base-03-js-numeri stringearray
 
Introduzione a Struts
Introduzione a StrutsIntroduzione a Struts
Introduzione a Struts
 
Hands on MVC - Mastering the Web
Hands on MVC - Mastering the WebHands on MVC - Mastering the Web
Hands on MVC - Mastering the Web
 
Talk introduzioneaspnetcore
Talk introduzioneaspnetcoreTalk introduzioneaspnetcore
Talk introduzioneaspnetcore
 
MyTask
MyTaskMyTask
MyTask
 
Blazor: are we ready for the launch?
Blazor: are we ready for the launch?Blazor: are we ready for the launch?
Blazor: are we ready for the launch?
 
Sviluppo web con Ruby on Rails
Sviluppo web con Ruby on RailsSviluppo web con Ruby on Rails
Sviluppo web con Ruby on Rails
 
Introduzione a Node.js
Introduzione a Node.jsIntroduzione a Node.js
Introduzione a Node.js
 
ASP.NET MVC 6 - uno sguardo al futuro
ASP.NET MVC 6 - uno sguardo al futuroASP.NET MVC 6 - uno sguardo al futuro
ASP.NET MVC 6 - uno sguardo al futuro
 
ASP.NET MVC Intro
ASP.NET MVC IntroASP.NET MVC Intro
ASP.NET MVC Intro
 
node.js e Postgresql
node.js e Postgresqlnode.js e Postgresql
node.js e Postgresql
 
Novità di Asp.Net 4.0
Novità di Asp.Net 4.0Novità di Asp.Net 4.0
Novità di Asp.Net 4.0
 
2014.04.04 Sviluppare applicazioni web (completamente) on line con Visual Stu...
2014.04.04 Sviluppare applicazioni web (completamente) on line con Visual Stu...2014.04.04 Sviluppare applicazioni web (completamente) on line con Visual Stu...
2014.04.04 Sviluppare applicazioni web (completamente) on line con Visual Stu...
 
Javascript task automation
Javascript task automationJavascript task automation
Javascript task automation
 

Techbar nodejs+mongodb+mongoose