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

PPTX
Marco Rho: Magento theme development workflow con Grunt
PDF
Roma linuxday 2013 - nodejs
PDF
PDF
Deploy MongoDB su Infrastruttura Amazon Web Services
PPTX
MongoDB
ODP
Linuxday2013
PDF
MongoDB
PDF
MongoDB Scala Roma SpringFramework Meeting2009
Marco Rho: Magento theme development workflow con Grunt
Roma linuxday 2013 - nodejs
Deploy MongoDB su Infrastruttura Amazon Web Services
MongoDB
Linuxday2013
MongoDB
MongoDB Scala Roma SpringFramework Meeting2009

Similar to Techbar nodejs+mongodb+mongoose (20)

PDF
MongoDb and Scala SpringFramework Meeting
PPSX
Introduzione mongodb
PPTX
Back to Basics, webinar 3: Riflessioni sulla progettazione degli schemi nei d...
PDF
Back-end: Guide for developers - Edit by Luca Marasca, Matteo Lupini, Nicolò ...
PDF
Acadevmy - GraphQL & Angular: Tutto il REST è noia!
PDF
MongoDB SpringFramework Meeting september 2009
PDF
MongoDB User Group Padova - Overviews iniziale su MongoDB
PDF
couchbase mobile
PPTX
Le novita di MongoDB 3.6
PPTX
J huery
PPTX
MongoDB - Back to Basics 2017 - Introduzione a NoSQL
PPTX
Back to Basics webinar 1 IT 17 - Introduzione ai NoSQL
PDF
Il Web orientato al futuro: Express, Angular e nodeJS
PDF
Introduzione a node.js
PDF
Introduzione a Node.js
PPTX
Session 02 - schema design e architettura
PPTX
20140311 app dev series - 01 - introduction - italian
PPTX
Back to Basics, webinar 1: Introduzione a NoSQL
PPTX
2014 it - app dev series - 04 - indicizzazione
PDF
MEAN: il nuovo stack di sviluppo per il futuro del web
MongoDb and Scala SpringFramework Meeting
Introduzione mongodb
Back to Basics, webinar 3: Riflessioni sulla progettazione degli schemi nei d...
Back-end: Guide for developers - Edit by Luca Marasca, Matteo Lupini, Nicolò ...
Acadevmy - GraphQL & Angular: Tutto il REST è noia!
MongoDB SpringFramework Meeting september 2009
MongoDB User Group Padova - Overviews iniziale su MongoDB
couchbase mobile
Le novita di MongoDB 3.6
J huery
MongoDB - Back to Basics 2017 - Introduzione a NoSQL
Back to Basics webinar 1 IT 17 - Introduzione ai NoSQL
Il Web orientato al futuro: Express, Angular e nodeJS
Introduzione a node.js
Introduzione a Node.js
Session 02 - schema design e architettura
20140311 app dev series - 01 - introduction - italian
Back to Basics, webinar 1: Introduzione a NoSQL
2014 it - app dev series - 04 - indicizzazione
MEAN: il nuovo stack di sviluppo per il futuro del web
Ad

Techbar nodejs+mongodb+mongoose