SlideShare a Scribd company logo
Using MongoDB with node.js
              Jonathan Altman
                  @async_io
               http://async.io/
        http://github.com/jonathana
              MongoDC 2011
what is node.js?
•   A non-browser Javascript toolkit/framework
    started by Ryan Dahl
•   Available for *nix-based systems: Linux, OS X, OpenSolaris, and now Windows
•   Built on top of Google’s V8 Javascript engine
•   Compatible with many common Javascript libraries out of the box via CommonJS
    support (http://www.commonjs.org/)
•   A batteries-included framework: HTTP and socket support baked into the core of the
    framework
•   A framework that is easy to build tooling on top of
•   Most importantly: asynchronous from the ground up


                                            2
what is node.js?
•   A non-browser Javascript toolkit/framework started by Ryan Dahl

•   Available for *nix-based systems: Linux, OS X,
    OpenSolaris, and now Windows
•   Built on top of Google’s V8 Javascript engine
•   Compatible with many common Javascript libraries out of the box via CommonJS
    support (http://www.commonjs.org/)
•   A batteries-included framework: HTTP and socket support baked into the core of the
    framework
•   A framework that is easy to build tooling on top of
•   Most importantly: asynchronous from the ground up


                                            3
what is node.js?
•   A non-browser Javascript toolkit/framework started by Ryan Dahl
•   Available for *nix-based systems: Linux, OS X, OpenSolaris, and now Windows

•   Built on top of Google’s V8 Javascript engine
•   Compatible with many common Javascript libraries out of the box via
    CommonJS support (http://www.commonjs.org/)
•   A batteries-included framework: HTTP and socket support baked into the
    core of the framework
•   A framework that is easy to build tooling on top of
•   Most importantly: asynchronous from the ground up


                                        4
what is node.js?
•   A non-browser Javascript toolkit/framework started by Ryan Dahl
•   Available for *nix-based systems: Linux, OS X, OpenSolaris, and now Windows
•   Built on top of Google’s V8 Javascript engine

•   Compatible with many common Javascript libraries out of
    the box via CommonJS support (http://www.commonjs.org/)
•   A batteries-included framework: HTTP and socket support baked into the
    core of the framework
•   A framework that is easy to build tooling on top of
•   Most importantly: asynchronous from the ground up


                                         5
what is node.js?
•   A non-browser Javascript toolkit/framework started by Ryan Dahl
•   Available for *nix-based systems: Linux, OS X, OpenSolaris, and now Windows
•   Built on top of Google’s V8 Javascript engine
•   Compatible with many common Javascript libraries out of the box via CommonJS
    support (http://www.commonjs.org/)

•   A batteries-included framework: HTTP and socket
    support baked into the core of the framework
•   A framework that is easy to build tooling on top of
•   Most importantly: asynchronous from the ground up



                                            6
what is node.js?
•   A non-browser Javascript toolkit/framework started by Ryan Dahl

•   Available for *nix-based systems: Linux, OS X, OpenSolaris, and now Windows

•   Built on top of Google’s V8 Javascript engine

•   Compatible with many common Javascript libraries out of the box via CommonJS
    support (http://www.commonjs.org/)

•   A batteries-included framework: HTTP and socket support baked into the core of
    the framework

•   A framework that is easy to build tooling on top of
•   Most importantly: asynchronous from the ground up



                                            7
what is node.js?
•   A non-browser Javascript toolkit/framework started by Ryan Dahl
•   Available for *nix-based systems: Linux, OS X, OpenSolaris, and now Windows
•   Built on top of Google’s V8 Javascript engine
•   Compatible with many common Javascript libraries out of the box via CommonJS
    support (http://www.commonjs.org/)
•   A batteries-included framework: HTTP and socket support baked into the core of the
    framework
•   A framework that is easy to build tooling on top of

•   Most importantly: asynchronous from the ground up

                                            8
getting started with node
• Longer than we have time for today
• I have some node.js resources pulled together at the
    end of the presentation
•   But (shameless plug) may I recommend http://
    www.slideshare.net/async_io/dcjq-nodejs-presentation
    as a good starting point?
why node with MongoDB?
• Both toolkits heavily leverage Javascript for their
  capabilities
• Commonality of programming language
• MongoDB’s speed/programming model is highly
  compatible with node’s asynchronous model
• Mostly compatible data types, but more on that later
using MongoDB in node.js
• connect-mongodb: web framework middleware for
  a MongoDB-backed session
• node-mongodb-native: native node driver for
  MongoDB
• mongoose: Javascript<->MongoDB object mapper
• mongolia: “non-magic” layer on the mongodb native
  driver
installing the packages
•   All packages are available through npm, the node package
    manager:
    npm install connect-mongodb
    npm install mongodb #(node-mongodb-
    native driver)
    npm install mongoose
    npm install mongolia
connect-mongodb
•   Provides MongoDB-backed session storage for the
    connect/express web development stack
•   connect: Middleware layer for node.js (think python WSGI
    or ruby’s rack for node)
•   Express: “Sinatra inspired web development framework for
    node.js -- insanely fast, flexible, and sexy”
•   We are going to examine use with Express
• npm    install express
wire connect-mongodb
       sessions into express
 var MongoDBSessionStore = require('connect-mongodb');

var app = module.exports = express.createServer(
	 express.bodyParser(),
	 express.methodOverride(),
	 express.cookieParser(),
	 // You *NEED* to use a better secret than this, and store it
in a better way...
	 express.session({store: new MongoDBSessionStore({ }), secret:
'foobar'})
);
get/set values from session
  req.session.pageRenders = req.session.pageRenders || 0;
req.session.pageRenders++;

// increment some view counts
if ( !req.session.viewCount)

   { req.session.viewCount = {};}

if ( !req.session.viewCount.hasOwnProperty(calledPage) )

 { req.session.viewCount[calledPage] = 0; }

req.session.viewCount[calledPage] += 1;
example app: heatNode
how much magic do you
       want?
    node MongoDB database drivers
node-mongodb-native driver
• Exposes the MongoDB API to node
• Fairly light wrapper
• Pushes the need to write library/utility/wrapper
  functionality onto the developer
• However, it has no preconceived vision of how to
  interact with MongoDB, and very little with node
node-mongodb code snippet
  var mongo = require('mongodb');
var Db= mongo.Db,
    ObjectID= mongo.BSONPure.BSON.ObjectID,
    Server= mongo.Server;

HeatmapProvider = function(host, port) {
   this.db= new Db('heatNode', new Server(host, port, {auto_reconnect: true}, {}));
   this.db.open(function(){});
};

HeatmapProvider.prototype.getCollection= function(callback) {
  this.db.collection('heatevents', function(error, heatevents_collection) {
    if( error ) callback(error);
    else callback(null, heatevents_collection);
  });
// Most of the *useful* code removed
mongoose: object mapping
        and persistence
• Declarative description of Javascript objects that can be
    persisted, retrieved, etc. with MongoDB
• Can provide defaults, constraints (validation), virtual
    (calculated) fields
•   Downside: reduces the plasticity of MongoDB
    document collections through its Schema
• Has several useful plugins built on top of it:
    authentication/authorization for example
using mongoose
•    Define a schema:
var mongoose = require('mongoose'),
	 Schema = mongoose.Schema;

var HeatEvent = new Schema({
	 type	 	 : { type: String, enum: ['click']}
	 , eventStamp	 : { type: Date,	 default: Date.now }
	 , payload	 : {
	 	 clickTarget	: String
	 	 , pageUrl	 : { type: String, index: true }
	 	 , clickPoint	 : {
	 	 	 X	 : Number
	 	 	 , Y	 : Number
	 	 }
	 }
});
HeatEvent.index({ 'type': 1, 'payload.pageUrl': 1});

var db = mongoose.connect('mongodb://localhost/heatNode');
module.exports = db.model('heatEvent', HeatEvent);
what did that schema buy us?
•   CRUD and various other operations pre-built
•   Constraints/Validation: built-in validation like this:
    : type		   : { type: String, enum: ['click']}

    or define your own callbacks
•   Defaults: ,   eventStamp	 : { type: Date,	
                                             default: Date.now }


•   Synthetic fields: map non-persisted values into/out of other
    persisted fields in the schema
mongolia: no-magic object
          mapping
• Layer built on top of the native mongodb driver
• Exposes the collection operations of the driver
• Provides a way to build type mapping
• Provides an event-hook system where you can build
  validations, defaulting, other features
• Not magic because it provides facilities for you to roll
  your own magic
tradeoffs in the drivers
• native mongodb driver: least overhead, but you
    will end up needing to customize on top
• mongolia: tools to build mapping, data type/casting
    support, event hooks. Some overhead, even for unused
    capabilities
• mongoose: full field-level declarative mapper, events;
    plugin system. “Full stack” object mapper, full overhead
•   More magic == more overhead
more info on node.js and
       resources
sample web development
             stack
•   node-inspector: debugging
•   express (and connect): web framework, middleware, routing, controllers, views
•   spark2: nice front-end for controlling node servers
•   ejs templates: embedded javascript, for views
•   connect-mongodb: mongoDB-backed sessions
•   mongoose: mongoDB-based object mapper for models
•   test: yeah, you should pick some and use them
•   jsdom: manipulate html DOMs server-side

•   jquery and/or YUI3: do cool stuff server side with the DOM
•   backbone: nifty client and server controller framework
•   socket.io: client/server Comet toolkit


                                                26
more from me on node.js
      and MongoDB:
• A longer presentation I did on what node.js is, and
  getting it up and running: http://www.slideshare.net/
  async_io/dcjq-nodejs-presentation
• Heatmapper app I built with node and MongoDB:
  https://github.com/jonathana/heatNode
more info on the packages:
• connect-mongodb: https://github.com/masylum/
  connect-mongodb
• node-mongodb-native: https://github.com/
  christkv/node-mongodb-native
• mongolia: https://github.com/masylum/mongolia
• mongoose: http://mongoosejs.com/ and https://
  github.com/learnboost/mongoose/
appendix: Resources
•   Ryan Dahl: (http://tinyclouds.org/, https://github.com/ry)
•   Ryan’s jsconf 2009 presentation: http://s3.amazonaws.com/four.livejournal/20091117/
    jsconf.pdf
•   Simon Willison’s blog post re: node.js: http://simonwillison.net/2009/Nov/23/node/
•   node.js home: http://nodejs.org/, git repo: https://github.com/joyent/node/
•   node modules: https://github.com/joyent/node/wiki/modules
•   Isaac Schlueter: (npm and nave) https://github.com/isaacs/, http://blog.izs.me/
•   Dav Glass’ mind-bending demonstration of using YUI server-side: http://
    developer.yahoo.com/yui/theater/video.php?v=glass-node
•   Nice list of some apps built using node.js + express: http://expressjs.com/
    applications.html


                                             29

More Related Content

What's hot

3 Things Everyone Knows About Node JS That You Don't
3 Things Everyone Knows About Node JS That You Don't3 Things Everyone Knows About Node JS That You Don't
3 Things Everyone Knows About Node JS That You Don't
F5 Buddy
 
Nodejs
NodejsNodejs
Developing realtime apps with Drupal and NodeJS
Developing realtime apps with Drupal and NodeJS Developing realtime apps with Drupal and NodeJS
Developing realtime apps with Drupal and NodeJS
drupalcampest
 
Introduction to node js - From "hello world" to deploying on azure
Introduction to node js - From "hello world" to deploying on azureIntroduction to node js - From "hello world" to deploying on azure
Introduction to node js - From "hello world" to deploying on azure
Colin Mackay
 
Scaling and hardware provisioning for databases (lessons learned at wikipedia)
Scaling and hardware provisioning for databases (lessons learned at wikipedia)Scaling and hardware provisioning for databases (lessons learned at wikipedia)
Scaling and hardware provisioning for databases (lessons learned at wikipedia)
Jaime Crespo
 
Building Lightning Fast Websites (for Twin Cities .NET User Group)
Building Lightning Fast Websites (for Twin Cities .NET User Group)Building Lightning Fast Websites (for Twin Cities .NET User Group)
Building Lightning Fast Websites (for Twin Cities .NET User Group)
strommen
 
Bringing Interactivity to Your Drupal Site with Node.js Integration
Bringing Interactivity to Your Drupal Site with Node.js IntegrationBringing Interactivity to Your Drupal Site with Node.js Integration
Bringing Interactivity to Your Drupal Site with Node.js Integration
Acquia
 
Node js for enterprise
Node js for enterpriseNode js for enterprise
Node js for enterprise
ravisankar munusamy
 
Csp and http headers
Csp and http headersCsp and http headers
Csp and http headers
ColdFusionConference
 
NodeJS ecosystem
NodeJS ecosystemNodeJS ecosystem
NodeJS ecosystem
Yukti Kaura
 
7 tips for javascript rich ajax websites
7 tips for javascript rich ajax websites7 tips for javascript rich ajax websites
7 tips for javascript rich ajax websitesoazabir
 
NodeJS
NodeJSNodeJS
Nodejs basics
Nodejs basicsNodejs basics
Nodejs basics
monikadeshmane
 
Node js Introduction
Node js IntroductionNode js Introduction
Node js Introduction
sanskriti agarwal
 
I Just Want to Run My Code: Waypoint, Nomad, and Other Things
I Just Want to Run My Code: Waypoint, Nomad, and Other ThingsI Just Want to Run My Code: Waypoint, Nomad, and Other Things
I Just Want to Run My Code: Waypoint, Nomad, and Other Things
Michael Lange
 
vert.x - asynchronous event-driven web applications on the JVM
vert.x - asynchronous event-driven web applications on the JVMvert.x - asynchronous event-driven web applications on the JVM
vert.x - asynchronous event-driven web applications on the JVM
jbandi
 
Node JS Crash Course
Node JS Crash CourseNode JS Crash Course
Node JS Crash Course
Haim Michael
 
Best node js course
Best node js courseBest node js course
Best node js course
bestonlinecoursescoupon
 

What's hot (20)

3 Things Everyone Knows About Node JS That You Don't
3 Things Everyone Knows About Node JS That You Don't3 Things Everyone Knows About Node JS That You Don't
3 Things Everyone Knows About Node JS That You Don't
 
Nodejs
NodejsNodejs
Nodejs
 
Developing realtime apps with Drupal and NodeJS
Developing realtime apps with Drupal and NodeJS Developing realtime apps with Drupal and NodeJS
Developing realtime apps with Drupal and NodeJS
 
Introduction to node js - From "hello world" to deploying on azure
Introduction to node js - From "hello world" to deploying on azureIntroduction to node js - From "hello world" to deploying on azure
Introduction to node js - From "hello world" to deploying on azure
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.js
 
Scaling and hardware provisioning for databases (lessons learned at wikipedia)
Scaling and hardware provisioning for databases (lessons learned at wikipedia)Scaling and hardware provisioning for databases (lessons learned at wikipedia)
Scaling and hardware provisioning for databases (lessons learned at wikipedia)
 
Building Lightning Fast Websites (for Twin Cities .NET User Group)
Building Lightning Fast Websites (for Twin Cities .NET User Group)Building Lightning Fast Websites (for Twin Cities .NET User Group)
Building Lightning Fast Websites (for Twin Cities .NET User Group)
 
Node js
Node jsNode js
Node js
 
Bringing Interactivity to Your Drupal Site with Node.js Integration
Bringing Interactivity to Your Drupal Site with Node.js IntegrationBringing Interactivity to Your Drupal Site with Node.js Integration
Bringing Interactivity to Your Drupal Site with Node.js Integration
 
Node js for enterprise
Node js for enterpriseNode js for enterprise
Node js for enterprise
 
Csp and http headers
Csp and http headersCsp and http headers
Csp and http headers
 
NodeJS ecosystem
NodeJS ecosystemNodeJS ecosystem
NodeJS ecosystem
 
7 tips for javascript rich ajax websites
7 tips for javascript rich ajax websites7 tips for javascript rich ajax websites
7 tips for javascript rich ajax websites
 
NodeJS
NodeJSNodeJS
NodeJS
 
Nodejs basics
Nodejs basicsNodejs basics
Nodejs basics
 
Node js Introduction
Node js IntroductionNode js Introduction
Node js Introduction
 
I Just Want to Run My Code: Waypoint, Nomad, and Other Things
I Just Want to Run My Code: Waypoint, Nomad, and Other ThingsI Just Want to Run My Code: Waypoint, Nomad, and Other Things
I Just Want to Run My Code: Waypoint, Nomad, and Other Things
 
vert.x - asynchronous event-driven web applications on the JVM
vert.x - asynchronous event-driven web applications on the JVMvert.x - asynchronous event-driven web applications on the JVM
vert.x - asynchronous event-driven web applications on the JVM
 
Node JS Crash Course
Node JS Crash CourseNode JS Crash Course
Node JS Crash Course
 
Best node js course
Best node js courseBest node js course
Best node js course
 

Viewers also liked

Presentazione GstarCAD
Presentazione GstarCADPresentazione GstarCAD
Presentazione GstarCAD
cgaldini
 
Iuavcamp presentazione
Iuavcamp presentazioneIuavcamp presentazione
Iuavcamp presentazioneenricodelfy
 
Iuavcamp presentazione
Iuavcamp presentazione Iuavcamp presentazione
Iuavcamp presentazione Giada15
 
Rivista Magazine free on-line CAD 2D and 3D - Settembre 2014 n° 4
Rivista Magazine free on-line CAD 2D and 3D - Settembre 2014 n° 4Rivista Magazine free on-line CAD 2D and 3D - Settembre 2014 n° 4
Rivista Magazine free on-line CAD 2D and 3D - Settembre 2014 n° 4
Costruzioni Edili Martini
 
Virtualizzazione postazioni grafiche - 3D.ITA Sinthera
Virtualizzazione postazioni grafiche - 3D.ITA SintheraVirtualizzazione postazioni grafiche - 3D.ITA Sinthera
Virtualizzazione postazioni grafiche - 3D.ITA Sinthera
Luca Turco
 
WPF basics
WPF basicsWPF basics
WPF basics
DotNetMarche
 
Gropius e il Bauhaus - Storia dell'Architettura Contemporanea
Gropius e il Bauhaus - Storia dell'Architettura ContemporaneaGropius e il Bauhaus - Storia dell'Architettura Contemporanea
Gropius e il Bauhaus - Storia dell'Architettura Contemporanea
Giacomo
 
Heritage o Historic BIM? La modellazione informativa per il patrimonio storic...
Heritage o Historic BIM? La modellazione informativa per il patrimonio storic...Heritage o Historic BIM? La modellazione informativa per il patrimonio storic...
Heritage o Historic BIM? La modellazione informativa per il patrimonio storic...
BIM group @ University of Padua
 
Coordinamento e progettazione integrata: dal bim execution plan alla creazion...
Coordinamento e progettazione integrata: dal bim execution plan alla creazion...Coordinamento e progettazione integrata: dal bim execution plan alla creazion...
Coordinamento e progettazione integrata: dal bim execution plan alla creazion...
BIM group @ University of Padua
 
A Guide to SlideShare Analytics - Excerpts from Hubspot's Step by Step Guide ...
A Guide to SlideShare Analytics - Excerpts from Hubspot's Step by Step Guide ...A Guide to SlideShare Analytics - Excerpts from Hubspot's Step by Step Guide ...
A Guide to SlideShare Analytics - Excerpts from Hubspot's Step by Step Guide ...SlideShare
 

Viewers also liked (11)

Presentazione GstarCAD
Presentazione GstarCADPresentazione GstarCAD
Presentazione GstarCAD
 
Iuavcamp presentazione
Iuavcamp presentazioneIuavcamp presentazione
Iuavcamp presentazione
 
Iuavcamp presentazione
Iuavcamp presentazione Iuavcamp presentazione
Iuavcamp presentazione
 
Rivista Magazine free on-line CAD 2D and 3D - Settembre 2014 n° 4
Rivista Magazine free on-line CAD 2D and 3D - Settembre 2014 n° 4Rivista Magazine free on-line CAD 2D and 3D - Settembre 2014 n° 4
Rivista Magazine free on-line CAD 2D and 3D - Settembre 2014 n° 4
 
Limiti
LimitiLimiti
Limiti
 
Virtualizzazione postazioni grafiche - 3D.ITA Sinthera
Virtualizzazione postazioni grafiche - 3D.ITA SintheraVirtualizzazione postazioni grafiche - 3D.ITA Sinthera
Virtualizzazione postazioni grafiche - 3D.ITA Sinthera
 
WPF basics
WPF basicsWPF basics
WPF basics
 
Gropius e il Bauhaus - Storia dell'Architettura Contemporanea
Gropius e il Bauhaus - Storia dell'Architettura ContemporaneaGropius e il Bauhaus - Storia dell'Architettura Contemporanea
Gropius e il Bauhaus - Storia dell'Architettura Contemporanea
 
Heritage o Historic BIM? La modellazione informativa per il patrimonio storic...
Heritage o Historic BIM? La modellazione informativa per il patrimonio storic...Heritage o Historic BIM? La modellazione informativa per il patrimonio storic...
Heritage o Historic BIM? La modellazione informativa per il patrimonio storic...
 
Coordinamento e progettazione integrata: dal bim execution plan alla creazion...
Coordinamento e progettazione integrata: dal bim execution plan alla creazion...Coordinamento e progettazione integrata: dal bim execution plan alla creazion...
Coordinamento e progettazione integrata: dal bim execution plan alla creazion...
 
A Guide to SlideShare Analytics - Excerpts from Hubspot's Step by Step Guide ...
A Guide to SlideShare Analytics - Excerpts from Hubspot's Step by Step Guide ...A Guide to SlideShare Analytics - Excerpts from Hubspot's Step by Step Guide ...
A Guide to SlideShare Analytics - Excerpts from Hubspot's Step by Step Guide ...
 

Similar to Mongo and node mongo dc 2011

Practical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.jsPractical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.js
async_io
 
Introduction to node.js by jiban
Introduction to node.js by jibanIntroduction to node.js by jiban
Introduction to node.js by jiban
Jibanananda Sana
 
Node.js In The Enterprise - A Primer
Node.js In The Enterprise - A PrimerNode.js In The Enterprise - A Primer
Node.js In The Enterprise - A Primer
Naveen S.R
 
An introduction to Node.js
An introduction to Node.jsAn introduction to Node.js
An introduction to Node.js
Kasey McCurdy
 
Tech io nodejs_20130531_v0.6
Tech io nodejs_20130531_v0.6Tech io nodejs_20130531_v0.6
Tech io nodejs_20130531_v0.6
Ganesh Kondal
 
Irfan maulana nodejs web development
Irfan maulana   nodejs web developmentIrfan maulana   nodejs web development
Irfan maulana nodejs web development
PHP Indonesia
 
PHP Indonesia - Nodejs Web Development
PHP Indonesia - Nodejs Web DevelopmentPHP Indonesia - Nodejs Web Development
PHP Indonesia - Nodejs Web Development
Irfan Maulana
 
Top 10 frameworks of node js
Top 10 frameworks of node jsTop 10 frameworks of node js
Top 10 frameworks of node js
Habilelabs
 
Introduction to node.js aka NodeJS
Introduction to node.js aka NodeJSIntroduction to node.js aka NodeJS
Introduction to node.js aka NodeJS
JITENDRA KUMAR PATEL
 
The MEAN Stack
The MEAN StackThe MEAN Stack
The MEAN Stack
Md. Ziaul Haq
 
NodeJS Presentation
NodeJS PresentationNodeJS Presentation
NodeJS Presentation
Faisal Shahzad Khan
 
Java script nirvana in netbeans [con5679]
Java script nirvana in netbeans [con5679]Java script nirvana in netbeans [con5679]
Java script nirvana in netbeans [con5679]
Ryan Cuprak
 
Nodejs overview
Nodejs overviewNodejs overview
Nodejs overview
Nicola Del Gobbo
 
What is Mean Stack Development ?
What is Mean Stack Development ?What is Mean Stack Development ?
What is Mean Stack Development ?
Balajihope
 
An Introduction to Node.js Development with Windows Azure
An Introduction to Node.js Development with Windows AzureAn Introduction to Node.js Development with Windows Azure
An Introduction to Node.js Development with Windows Azure
Troy Miles
 
End-to-end W3C APIs - tpac 2012
End-to-end W3C APIs - tpac 2012End-to-end W3C APIs - tpac 2012
End-to-end W3C APIs - tpac 2012
Alexandre Morgaut
 
Beginners Node.js
Beginners Node.jsBeginners Node.js
Beginners Node.js
Khaled Mosharraf
 
Node js (runtime environment + js library) platform
Node js (runtime environment + js library) platformNode js (runtime environment + js library) platform
Node js (runtime environment + js library) platform
Sreenivas Kappala
 
NodeJS - Server Side JS
NodeJS - Server Side JS NodeJS - Server Side JS
NodeJS - Server Side JS
Ganesh Kondal
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.js
orkaplan
 

Similar to Mongo and node mongo dc 2011 (20)

Practical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.jsPractical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.js
 
Introduction to node.js by jiban
Introduction to node.js by jibanIntroduction to node.js by jiban
Introduction to node.js by jiban
 
Node.js In The Enterprise - A Primer
Node.js In The Enterprise - A PrimerNode.js In The Enterprise - A Primer
Node.js In The Enterprise - A Primer
 
An introduction to Node.js
An introduction to Node.jsAn introduction to Node.js
An introduction to Node.js
 
Tech io nodejs_20130531_v0.6
Tech io nodejs_20130531_v0.6Tech io nodejs_20130531_v0.6
Tech io nodejs_20130531_v0.6
 
Irfan maulana nodejs web development
Irfan maulana   nodejs web developmentIrfan maulana   nodejs web development
Irfan maulana nodejs web development
 
PHP Indonesia - Nodejs Web Development
PHP Indonesia - Nodejs Web DevelopmentPHP Indonesia - Nodejs Web Development
PHP Indonesia - Nodejs Web Development
 
Top 10 frameworks of node js
Top 10 frameworks of node jsTop 10 frameworks of node js
Top 10 frameworks of node js
 
Introduction to node.js aka NodeJS
Introduction to node.js aka NodeJSIntroduction to node.js aka NodeJS
Introduction to node.js aka NodeJS
 
The MEAN Stack
The MEAN StackThe MEAN Stack
The MEAN Stack
 
NodeJS Presentation
NodeJS PresentationNodeJS Presentation
NodeJS Presentation
 
Java script nirvana in netbeans [con5679]
Java script nirvana in netbeans [con5679]Java script nirvana in netbeans [con5679]
Java script nirvana in netbeans [con5679]
 
Nodejs overview
Nodejs overviewNodejs overview
Nodejs overview
 
What is Mean Stack Development ?
What is Mean Stack Development ?What is Mean Stack Development ?
What is Mean Stack Development ?
 
An Introduction to Node.js Development with Windows Azure
An Introduction to Node.js Development with Windows AzureAn Introduction to Node.js Development with Windows Azure
An Introduction to Node.js Development with Windows Azure
 
End-to-end W3C APIs - tpac 2012
End-to-end W3C APIs - tpac 2012End-to-end W3C APIs - tpac 2012
End-to-end W3C APIs - tpac 2012
 
Beginners Node.js
Beginners Node.jsBeginners Node.js
Beginners Node.js
 
Node js (runtime environment + js library) platform
Node js (runtime environment + js library) platformNode js (runtime environment + js library) platform
Node js (runtime environment + js library) platform
 
NodeJS - Server Side JS
NodeJS - Server Side JS NodeJS - Server Side JS
NodeJS - Server Side JS
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.js
 

More from async_io

Lessons Learned from Building a REST API on Google App Engine
Lessons Learned from Building a REST API on Google App EngineLessons Learned from Building a REST API on Google App Engine
Lessons Learned from Building a REST API on Google App Engine
async_io
 
Guide to AngularJS Services - NOVA MEAN August 2014
Guide to AngularJS Services - NOVA MEAN August 2014Guide to AngularJS Services - NOVA MEAN August 2014
Guide to AngularJS Services - NOVA MEAN August 2014
async_io
 
NOVA MEAN - Why the M in MEAN is a Significant Contributor to Its Success
NOVA MEAN - Why the M in MEAN is a Significant Contributor to Its SuccessNOVA MEAN - Why the M in MEAN is a Significant Contributor to Its Success
NOVA MEAN - Why the M in MEAN is a Significant Contributor to Its Success
async_io
 
Building a Cauldron for Chef to Cook In
Building a Cauldron for Chef to Cook InBuilding a Cauldron for Chef to Cook In
Building a Cauldron for Chef to Cook In
async_io
 
Using npm to Manage Your Projects for Fun and Profit - USEFUL INFO IN NOTES!
Using npm to Manage Your Projects for Fun and Profit - USEFUL INFO IN NOTES!Using npm to Manage Your Projects for Fun and Profit - USEFUL INFO IN NOTES!
Using npm to Manage Your Projects for Fun and Profit - USEFUL INFO IN NOTES!
async_io
 
Javascript Promises/Q Library
Javascript Promises/Q LibraryJavascript Promises/Q Library
Javascript Promises/Q Library
async_io
 
Using Jython To Prototype Mahout Code
Using Jython To Prototype Mahout CodeUsing Jython To Prototype Mahout Code
Using Jython To Prototype Mahout Code
async_io
 

More from async_io (7)

Lessons Learned from Building a REST API on Google App Engine
Lessons Learned from Building a REST API on Google App EngineLessons Learned from Building a REST API on Google App Engine
Lessons Learned from Building a REST API on Google App Engine
 
Guide to AngularJS Services - NOVA MEAN August 2014
Guide to AngularJS Services - NOVA MEAN August 2014Guide to AngularJS Services - NOVA MEAN August 2014
Guide to AngularJS Services - NOVA MEAN August 2014
 
NOVA MEAN - Why the M in MEAN is a Significant Contributor to Its Success
NOVA MEAN - Why the M in MEAN is a Significant Contributor to Its SuccessNOVA MEAN - Why the M in MEAN is a Significant Contributor to Its Success
NOVA MEAN - Why the M in MEAN is a Significant Contributor to Its Success
 
Building a Cauldron for Chef to Cook In
Building a Cauldron for Chef to Cook InBuilding a Cauldron for Chef to Cook In
Building a Cauldron for Chef to Cook In
 
Using npm to Manage Your Projects for Fun and Profit - USEFUL INFO IN NOTES!
Using npm to Manage Your Projects for Fun and Profit - USEFUL INFO IN NOTES!Using npm to Manage Your Projects for Fun and Profit - USEFUL INFO IN NOTES!
Using npm to Manage Your Projects for Fun and Profit - USEFUL INFO IN NOTES!
 
Javascript Promises/Q Library
Javascript Promises/Q LibraryJavascript Promises/Q Library
Javascript Promises/Q Library
 
Using Jython To Prototype Mahout Code
Using Jython To Prototype Mahout CodeUsing Jython To Prototype Mahout Code
Using Jython To Prototype Mahout Code
 

Recently uploaded

Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
James Anderson
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
Alex Pruden
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
Peter Spielvogel
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Nexer Digital
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
KAMESHS29
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
SOFTTECHHUB
 
The Metaverse and AI: how can decision-makers harness the Metaverse for their...
The Metaverse and AI: how can decision-makers harness the Metaverse for their...The Metaverse and AI: how can decision-makers harness the Metaverse for their...
The Metaverse and AI: how can decision-makers harness the Metaverse for their...
Jen Stirrup
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
nkrafacyberclub
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 

Recently uploaded (20)

Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
 
The Metaverse and AI: how can decision-makers harness the Metaverse for their...
The Metaverse and AI: how can decision-makers harness the Metaverse for their...The Metaverse and AI: how can decision-makers harness the Metaverse for their...
The Metaverse and AI: how can decision-makers harness the Metaverse for their...
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 

Mongo and node mongo dc 2011

  • 1. Using MongoDB with node.js Jonathan Altman @async_io http://async.io/ http://github.com/jonathana MongoDC 2011
  • 2. what is node.js? • A non-browser Javascript toolkit/framework started by Ryan Dahl • Available for *nix-based systems: Linux, OS X, OpenSolaris, and now Windows • Built on top of Google’s V8 Javascript engine • Compatible with many common Javascript libraries out of the box via CommonJS support (http://www.commonjs.org/) • A batteries-included framework: HTTP and socket support baked into the core of the framework • A framework that is easy to build tooling on top of • Most importantly: asynchronous from the ground up 2
  • 3. what is node.js? • A non-browser Javascript toolkit/framework started by Ryan Dahl • Available for *nix-based systems: Linux, OS X, OpenSolaris, and now Windows • Built on top of Google’s V8 Javascript engine • Compatible with many common Javascript libraries out of the box via CommonJS support (http://www.commonjs.org/) • A batteries-included framework: HTTP and socket support baked into the core of the framework • A framework that is easy to build tooling on top of • Most importantly: asynchronous from the ground up 3
  • 4. what is node.js? • A non-browser Javascript toolkit/framework started by Ryan Dahl • Available for *nix-based systems: Linux, OS X, OpenSolaris, and now Windows • Built on top of Google’s V8 Javascript engine • Compatible with many common Javascript libraries out of the box via CommonJS support (http://www.commonjs.org/) • A batteries-included framework: HTTP and socket support baked into the core of the framework • A framework that is easy to build tooling on top of • Most importantly: asynchronous from the ground up 4
  • 5. what is node.js? • A non-browser Javascript toolkit/framework started by Ryan Dahl • Available for *nix-based systems: Linux, OS X, OpenSolaris, and now Windows • Built on top of Google’s V8 Javascript engine • Compatible with many common Javascript libraries out of the box via CommonJS support (http://www.commonjs.org/) • A batteries-included framework: HTTP and socket support baked into the core of the framework • A framework that is easy to build tooling on top of • Most importantly: asynchronous from the ground up 5
  • 6. what is node.js? • A non-browser Javascript toolkit/framework started by Ryan Dahl • Available for *nix-based systems: Linux, OS X, OpenSolaris, and now Windows • Built on top of Google’s V8 Javascript engine • Compatible with many common Javascript libraries out of the box via CommonJS support (http://www.commonjs.org/) • A batteries-included framework: HTTP and socket support baked into the core of the framework • A framework that is easy to build tooling on top of • Most importantly: asynchronous from the ground up 6
  • 7. what is node.js? • A non-browser Javascript toolkit/framework started by Ryan Dahl • Available for *nix-based systems: Linux, OS X, OpenSolaris, and now Windows • Built on top of Google’s V8 Javascript engine • Compatible with many common Javascript libraries out of the box via CommonJS support (http://www.commonjs.org/) • A batteries-included framework: HTTP and socket support baked into the core of the framework • A framework that is easy to build tooling on top of • Most importantly: asynchronous from the ground up 7
  • 8. what is node.js? • A non-browser Javascript toolkit/framework started by Ryan Dahl • Available for *nix-based systems: Linux, OS X, OpenSolaris, and now Windows • Built on top of Google’s V8 Javascript engine • Compatible with many common Javascript libraries out of the box via CommonJS support (http://www.commonjs.org/) • A batteries-included framework: HTTP and socket support baked into the core of the framework • A framework that is easy to build tooling on top of • Most importantly: asynchronous from the ground up 8
  • 9. getting started with node • Longer than we have time for today • I have some node.js resources pulled together at the end of the presentation • But (shameless plug) may I recommend http:// www.slideshare.net/async_io/dcjq-nodejs-presentation as a good starting point?
  • 10. why node with MongoDB? • Both toolkits heavily leverage Javascript for their capabilities • Commonality of programming language • MongoDB’s speed/programming model is highly compatible with node’s asynchronous model • Mostly compatible data types, but more on that later
  • 11. using MongoDB in node.js • connect-mongodb: web framework middleware for a MongoDB-backed session • node-mongodb-native: native node driver for MongoDB • mongoose: Javascript<->MongoDB object mapper • mongolia: “non-magic” layer on the mongodb native driver
  • 12. installing the packages • All packages are available through npm, the node package manager: npm install connect-mongodb npm install mongodb #(node-mongodb- native driver) npm install mongoose npm install mongolia
  • 13. connect-mongodb • Provides MongoDB-backed session storage for the connect/express web development stack • connect: Middleware layer for node.js (think python WSGI or ruby’s rack for node) • Express: “Sinatra inspired web development framework for node.js -- insanely fast, flexible, and sexy” • We are going to examine use with Express • npm install express
  • 14. wire connect-mongodb sessions into express var MongoDBSessionStore = require('connect-mongodb'); var app = module.exports = express.createServer( express.bodyParser(), express.methodOverride(), express.cookieParser(), // You *NEED* to use a better secret than this, and store it in a better way... express.session({store: new MongoDBSessionStore({ }), secret: 'foobar'}) );
  • 15. get/set values from session req.session.pageRenders = req.session.pageRenders || 0; req.session.pageRenders++; // increment some view counts if ( !req.session.viewCount) { req.session.viewCount = {};} if ( !req.session.viewCount.hasOwnProperty(calledPage) ) { req.session.viewCount[calledPage] = 0; } req.session.viewCount[calledPage] += 1;
  • 17. how much magic do you want? node MongoDB database drivers
  • 18. node-mongodb-native driver • Exposes the MongoDB API to node • Fairly light wrapper • Pushes the need to write library/utility/wrapper functionality onto the developer • However, it has no preconceived vision of how to interact with MongoDB, and very little with node
  • 19. node-mongodb code snippet var mongo = require('mongodb'); var Db= mongo.Db, ObjectID= mongo.BSONPure.BSON.ObjectID, Server= mongo.Server; HeatmapProvider = function(host, port) { this.db= new Db('heatNode', new Server(host, port, {auto_reconnect: true}, {})); this.db.open(function(){}); }; HeatmapProvider.prototype.getCollection= function(callback) { this.db.collection('heatevents', function(error, heatevents_collection) { if( error ) callback(error); else callback(null, heatevents_collection); }); // Most of the *useful* code removed
  • 20. mongoose: object mapping and persistence • Declarative description of Javascript objects that can be persisted, retrieved, etc. with MongoDB • Can provide defaults, constraints (validation), virtual (calculated) fields • Downside: reduces the plasticity of MongoDB document collections through its Schema • Has several useful plugins built on top of it: authentication/authorization for example
  • 21. using mongoose • Define a schema: var mongoose = require('mongoose'), Schema = mongoose.Schema; var HeatEvent = new Schema({ type : { type: String, enum: ['click']} , eventStamp : { type: Date, default: Date.now } , payload : { clickTarget : String , pageUrl : { type: String, index: true } , clickPoint : { X : Number , Y : Number } } }); HeatEvent.index({ 'type': 1, 'payload.pageUrl': 1}); var db = mongoose.connect('mongodb://localhost/heatNode'); module.exports = db.model('heatEvent', HeatEvent);
  • 22. what did that schema buy us? • CRUD and various other operations pre-built • Constraints/Validation: built-in validation like this: : type : { type: String, enum: ['click']} or define your own callbacks • Defaults: , eventStamp : { type: Date, default: Date.now } • Synthetic fields: map non-persisted values into/out of other persisted fields in the schema
  • 23. mongolia: no-magic object mapping • Layer built on top of the native mongodb driver • Exposes the collection operations of the driver • Provides a way to build type mapping • Provides an event-hook system where you can build validations, defaulting, other features • Not magic because it provides facilities for you to roll your own magic
  • 24. tradeoffs in the drivers • native mongodb driver: least overhead, but you will end up needing to customize on top • mongolia: tools to build mapping, data type/casting support, event hooks. Some overhead, even for unused capabilities • mongoose: full field-level declarative mapper, events; plugin system. “Full stack” object mapper, full overhead • More magic == more overhead
  • 25. more info on node.js and resources
  • 26. sample web development stack • node-inspector: debugging • express (and connect): web framework, middleware, routing, controllers, views • spark2: nice front-end for controlling node servers • ejs templates: embedded javascript, for views • connect-mongodb: mongoDB-backed sessions • mongoose: mongoDB-based object mapper for models • test: yeah, you should pick some and use them • jsdom: manipulate html DOMs server-side • jquery and/or YUI3: do cool stuff server side with the DOM • backbone: nifty client and server controller framework • socket.io: client/server Comet toolkit 26
  • 27. more from me on node.js and MongoDB: • A longer presentation I did on what node.js is, and getting it up and running: http://www.slideshare.net/ async_io/dcjq-nodejs-presentation • Heatmapper app I built with node and MongoDB: https://github.com/jonathana/heatNode
  • 28. more info on the packages: • connect-mongodb: https://github.com/masylum/ connect-mongodb • node-mongodb-native: https://github.com/ christkv/node-mongodb-native • mongolia: https://github.com/masylum/mongolia • mongoose: http://mongoosejs.com/ and https:// github.com/learnboost/mongoose/
  • 29. appendix: Resources • Ryan Dahl: (http://tinyclouds.org/, https://github.com/ry) • Ryan’s jsconf 2009 presentation: http://s3.amazonaws.com/four.livejournal/20091117/ jsconf.pdf • Simon Willison’s blog post re: node.js: http://simonwillison.net/2009/Nov/23/node/ • node.js home: http://nodejs.org/, git repo: https://github.com/joyent/node/ • node modules: https://github.com/joyent/node/wiki/modules • Isaac Schlueter: (npm and nave) https://github.com/isaacs/, http://blog.izs.me/ • Dav Glass’ mind-bending demonstration of using YUI server-side: http:// developer.yahoo.com/yui/theater/video.php?v=glass-node • Nice list of some apps built using node.js + express: http://expressjs.com/ applications.html 29

Editor's Notes

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n