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 (20)

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

Viewers also liked (11)

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

Similar to Mongo and node mongo dc 2011 (20)

PPTX
Node js installation steps.pptx slide share ppts
HemaSenthil5
 
PPTX
module for backend full stack applications 1.pptx
hemalathas752360
 
KEY
Practical Use of MongoDB for Node.js
async_io
 
PDF
Node.js for beginner
Sarunyhot Suwannachoti
 
PPTX
What is Mean Stack Development ?
Balajihope
 
PPTX
Kalp Corporate Node JS Perfect Guide
Kalp Corporate
 
PPTX
Introduction to Node.js
Vikash Singh
 
PPTX
After the LAMP, it's time to get MEAN
Jeff Fox
 
PPTX
Intro to node and mongodb 1
Mohammad Qureshi
 
PPTX
Introduction to node.js
Md. Sohel Rana
 
PPTX
Beginners Node.js
Khaled Mosharraf
 
ODP
Sfd hanoi2012 nguyen ha duong yang node.js-intro
Vu Hung Nguyen
 
ODP
Sfd2012Hanoi Nguyễn Hà Dương - Introduction to Node.js
Vu Hung Nguyen
 
PDF
An introduction to Node.js
Kasey McCurdy
 
PPTX
Oracle application container cloud back end integration using node final
Getting value from IoT, Integration and Data Analytics
 
PPTX
Introduction to Node.js
Winston Hsieh
 
PPTX
mearn-stack-new_ccvbhbhvgvgcdszsxdxfcf.pptx
aravym456
 
PDF
What is mean stack?
Rishabh Saxena
 
ODP
Introduce about Nodejs - duyetdev.com
Van-Duyet Le
 
PDF
Node, express & sails
Brian Shannon
 
Node js installation steps.pptx slide share ppts
HemaSenthil5
 
module for backend full stack applications 1.pptx
hemalathas752360
 
Practical Use of MongoDB for Node.js
async_io
 
Node.js for beginner
Sarunyhot Suwannachoti
 
What is Mean Stack Development ?
Balajihope
 
Kalp Corporate Node JS Perfect Guide
Kalp Corporate
 
Introduction to Node.js
Vikash Singh
 
After the LAMP, it's time to get MEAN
Jeff Fox
 
Intro to node and mongodb 1
Mohammad Qureshi
 
Introduction to node.js
Md. Sohel Rana
 
Beginners Node.js
Khaled Mosharraf
 
Sfd hanoi2012 nguyen ha duong yang node.js-intro
Vu Hung Nguyen
 
Sfd2012Hanoi Nguyễn Hà Dương - Introduction to Node.js
Vu Hung Nguyen
 
An introduction to Node.js
Kasey McCurdy
 
Oracle application container cloud back end integration using node final
Getting value from IoT, Integration and Data Analytics
 
Introduction to Node.js
Winston Hsieh
 
mearn-stack-new_ccvbhbhvgvgcdszsxdxfcf.pptx
aravym456
 
What is mean stack?
Rishabh Saxena
 
Introduce about Nodejs - duyetdev.com
Van-Duyet Le
 
Node, express & sails
Brian Shannon
 
Ad

More from async_io (7)

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

Recently uploaded (20)

PDF
''Taming Explosive Growth: Building Resilience in a Hyper-Scaled Financial Pl...
Fwdays
 
PDF
TrustArc Webinar - Navigating APAC Data Privacy Laws: Compliance & Challenges
TrustArc
 
PDF
Supporting the NextGen 911 Digital Transformation with FME
Safe Software
 
PDF
GDG Cloud Southlake #44: Eyal Bukchin: Tightening the Kubernetes Feedback Loo...
James Anderson
 
PDF
How to Comply With Saudi Arabia’s National Cybersecurity Regulations.pdf
Bluechip Advanced Technologies
 
PPSX
Usergroup - OutSystems Architecture.ppsx
Kurt Vandevelde
 
PDF
Simplify Your FME Flow Setup: Fault-Tolerant Deployment Made Easy with Packer...
Safe Software
 
PDF
Automating the Geo-Referencing of Historic Aerial Photography in Flanders
Safe Software
 
PDF
“A Re-imagination of Embedded Vision System Design,” a Presentation from Imag...
Edge AI and Vision Alliance
 
PDF
Dev Dives: Accelerating agentic automation with Autopilot for Everyone
UiPathCommunity
 
PDF
Optimizing the trajectory of a wheel loader working in short loading cycles
Reno Filla
 
PPTX
2025 HackRedCon Cyber Career Paths.pptx Scott Stanton
Scott Stanton
 
PDF
FME as an Orchestration Tool with Principles From Data Gravity
Safe Software
 
PDF
Why aren't you using FME Flow's CPU Time?
Safe Software
 
PDF
Quantum Threats Are Closer Than You Think – Act Now to Stay Secure
WSO2
 
PDF
ArcGIS Utility Network Migration - The Hunter Water Story
Safe Software
 
PPTX
Reimaginando la Ciberdefensa: De Copilots a Redes de Agentes
Cristian Garcia G.
 
PDF
DoS Attack vs DDoS Attack_ The Silent Wars of the Internet.pdf
CyberPro Magazine
 
PDF
Understanding AI Optimization AIO, LLMO, and GEO
CoDigital
 
PDF
5 Things to Consider When Deploying AI in Your Enterprise
Safe Software
 
''Taming Explosive Growth: Building Resilience in a Hyper-Scaled Financial Pl...
Fwdays
 
TrustArc Webinar - Navigating APAC Data Privacy Laws: Compliance & Challenges
TrustArc
 
Supporting the NextGen 911 Digital Transformation with FME
Safe Software
 
GDG Cloud Southlake #44: Eyal Bukchin: Tightening the Kubernetes Feedback Loo...
James Anderson
 
How to Comply With Saudi Arabia’s National Cybersecurity Regulations.pdf
Bluechip Advanced Technologies
 
Usergroup - OutSystems Architecture.ppsx
Kurt Vandevelde
 
Simplify Your FME Flow Setup: Fault-Tolerant Deployment Made Easy with Packer...
Safe Software
 
Automating the Geo-Referencing of Historic Aerial Photography in Flanders
Safe Software
 
“A Re-imagination of Embedded Vision System Design,” a Presentation from Imag...
Edge AI and Vision Alliance
 
Dev Dives: Accelerating agentic automation with Autopilot for Everyone
UiPathCommunity
 
Optimizing the trajectory of a wheel loader working in short loading cycles
Reno Filla
 
2025 HackRedCon Cyber Career Paths.pptx Scott Stanton
Scott Stanton
 
FME as an Orchestration Tool with Principles From Data Gravity
Safe Software
 
Why aren't you using FME Flow's CPU Time?
Safe Software
 
Quantum Threats Are Closer Than You Think – Act Now to Stay Secure
WSO2
 
ArcGIS Utility Network Migration - The Hunter Water Story
Safe Software
 
Reimaginando la Ciberdefensa: De Copilots a Redes de Agentes
Cristian Garcia G.
 
DoS Attack vs DDoS Attack_ The Silent Wars of the Internet.pdf
CyberPro Magazine
 
Understanding AI Optimization AIO, LLMO, and GEO
CoDigital
 
5 Things to Consider When Deploying AI in Your Enterprise
Safe Software
 

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