SlideShare a Scribd company logo
Introduction to
 asynchronous DB access
using Node.js and MongoDB


 Adrien Joly
 adrien@whyd.com
1. Synchronous db query


var db = DB.open("localhost:28000");

var cars = db.collection("cars");

var redCars = cars.find({color: "red"});

console.log(redCars);



    synchronous calls => sequential flow => simple :-)
2. Asynchronous db query

DB.open("localhost:28000", function(err, db) {

  db.collection("cars", function(err, cars) {

      cars.find({color: "red"}, function(err, res) {

        console.log(res);

      });

  });

});

            asynchronous calls => callback functions
3. Separate view from controller (MVC)

db.js (model)
DB.open("localhost:28000", function(err, db) {
  db.collection("cars", function(err, cars) {
    exports.getRedCars = function(callback) {
      cars.query({color: "red"}, callback);
    });
  });
});

controller.js
var model = require("db");
var renderRedCars = function() {
 model.getRedCars(function(err, redCars) {
      console.log(redCars);
   });
};
4. Towards more models
db.js
DB.open("localhost:28000", function(err, db) {
  exports.getCollection = function(name, callback) {
    db.collection(name, callback);
  };
});

cars.js (model)
require("db").getCollection("cars", function(err, cars) {
    exports.getRedCars = function(callback) {
      cars.query({color: "red"}, callback);
    });
  });
});

controller.js
var renderRedCars = function() {
 require("cars").getRedCars(function(err, redCars) {
      console.log(redCars);
   });
};
5. Optimization, #fail safety
start_server.js (main node.js application)
require("db").init(function() {
  // start your application (->controllers->models) here
});

db.js
exports.init = function (initCallback) {
  DB.open("localhost:28000", function(err, db) {
    exports.getCollection = function(name, callback) {
      db.collection(name, callback);
    };
  initCallback();
});

(models and controllers)
...
References

required stuff
http://nodejs.org/
http://www.mongodb.org/
https://github.com/christkv/node-mongodb-native


about asynchronous DB access
http://stackoverflow.com/questions/6275643/node-js-design-pattern-for-creating-
db-connection-once




invite to request :-p
http://whyd.com/

More Related Content

What's hot (20)

PDF
Map kit light
CocoaHeads France
 
PDF
Consuming Web Services with Swift and Rx
Guillermo Gonzalez
 
PDF
Umleitung: a tiny mochiweb/CouchDB app
Lenz Gschwendtner
 
PDF
FalsyValues. Dmitry Soshnikov - ECMAScript 6
Dmitry Soshnikov
 
PDF
Otimizando Aplicações em Rails
Juan Maiz
 
PDF
Ruby on Rails Oracle adaptera izstrāde
Raimonds Simanovskis
 
KEY
Psgi Plack Sfpm
som_nangia
 
PDF
Callbacks and control flow in Node js
Thomas Roch
 
PDF
Introduction to reactive programming & ReactiveCocoa
Florent Pillet
 
KEY
New Design of OneRing
Qiangning Hong
 
PPT
Mobile webapplication development
Ganesh Gembali
 
PDF
What's New in ES6 for Web Devs
Rami Sayar
 
PDF
Using Node.js to Build Great Streaming Services - HTML5 Dev Conf
Tom Croucher
 
PPTX
Advanced JavaScript
Mahmoud Tolba
 
KEY
Wider than rails
Alexey Nayden
 
PPT
Async programming on NET
yuyijq
 
PDF
OneRing @ OSCamp 2010
Qiangning Hong
 
PDF
Mini Rails Framework
Aviandri Rivai
 
PDF
Matthew Eernisse, NodeJs, .toster {webdev}
.toster
 
Map kit light
CocoaHeads France
 
Consuming Web Services with Swift and Rx
Guillermo Gonzalez
 
Umleitung: a tiny mochiweb/CouchDB app
Lenz Gschwendtner
 
FalsyValues. Dmitry Soshnikov - ECMAScript 6
Dmitry Soshnikov
 
Otimizando Aplicações em Rails
Juan Maiz
 
Ruby on Rails Oracle adaptera izstrāde
Raimonds Simanovskis
 
Psgi Plack Sfpm
som_nangia
 
Callbacks and control flow in Node js
Thomas Roch
 
Introduction to reactive programming & ReactiveCocoa
Florent Pillet
 
New Design of OneRing
Qiangning Hong
 
Mobile webapplication development
Ganesh Gembali
 
What's New in ES6 for Web Devs
Rami Sayar
 
Using Node.js to Build Great Streaming Services - HTML5 Dev Conf
Tom Croucher
 
Advanced JavaScript
Mahmoud Tolba
 
Wider than rails
Alexey Nayden
 
Async programming on NET
yuyijq
 
OneRing @ OSCamp 2010
Qiangning Hong
 
Mini Rails Framework
Aviandri Rivai
 
Matthew Eernisse, NodeJs, .toster {webdev}
.toster
 

Similar to Introduction to asynchronous DB access using Node.js and MongoDB (20)

PDF
Mongoskin - Guilin
Jackson Tian
 
PDF
Dependency Management with RequireJS
Aaronius
 
ZIP
Javascript Everywhere From Nose To Tail
Cliffano Subagio
 
PDF
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
Guy Royse
 
PPTX
IndexedDB - Querying and Performance
Parashuram N
 
PPTX
Designing REST API automation tests in Kotlin
Dmitriy Sobko
 
PDF
Future of Web Apps: Google Gears
dion
 
PPTX
Getting Started with MongoDB and NodeJS
MongoDB
 
PDF
mongodb-introduction
Tse-Ching Ho
 
PPTX
Developing web-apps like it's 2013
Laurent_VB
 
PDF
Rails 6 frontend frameworks
Eric Guo
 
PDF
SproutCore and the Future of Web Apps
Mike Subelsky
 
PPT
GHC Participant Training
AidIQ
 
PDF
DataMapper
Yehuda Katz
 
PDF
jQuery and Rails: Best Friends Forever
stephskardal
 
PDF
Fast Web Applications Development with Ruby on Rails on Oracle
Raimonds Simanovskis
 
PDF
JavaScript Core
François Sarradin
 
PDF
MongoDB and RDBMS
francescapasha
 
PPT
Backbone js
husnara mohammad
 
PPTX
Internet and Web Technology (CLASS-10) [Node.js] | NIC/NIELIT Web Technology
Ayes Chinmay
 
Mongoskin - Guilin
Jackson Tian
 
Dependency Management with RequireJS
Aaronius
 
Javascript Everywhere From Nose To Tail
Cliffano Subagio
 
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
Guy Royse
 
IndexedDB - Querying and Performance
Parashuram N
 
Designing REST API automation tests in Kotlin
Dmitriy Sobko
 
Future of Web Apps: Google Gears
dion
 
Getting Started with MongoDB and NodeJS
MongoDB
 
mongodb-introduction
Tse-Ching Ho
 
Developing web-apps like it's 2013
Laurent_VB
 
Rails 6 frontend frameworks
Eric Guo
 
SproutCore and the Future of Web Apps
Mike Subelsky
 
GHC Participant Training
AidIQ
 
DataMapper
Yehuda Katz
 
jQuery and Rails: Best Friends Forever
stephskardal
 
Fast Web Applications Development with Ruby on Rails on Oracle
Raimonds Simanovskis
 
JavaScript Core
François Sarradin
 
MongoDB and RDBMS
francescapasha
 
Backbone js
husnara mohammad
 
Internet and Web Technology (CLASS-10) [Node.js] | NIC/NIELIT Web Technology
Ayes Chinmay
 
Ad

More from Adrien Joly (9)

PPT
PhD Defense - A Context Management Framework based on Wisdom of Crowds for So...
Adrien Joly
 
PPT
Contextual Recommendation of Social Updates, a tag-based framework
Adrien Joly
 
PPT
Exploitation de données de contexte utilisateur pour estimer la pertinence d...
Adrien Joly
 
PPT
Tangible Contextual Tag Clouds towards Controlled and Relevant Social Inter...
Adrien Joly
 
PPT
Natural Ubiquitous Call-out
Adrien Joly
 
PPT
Workspace Awareness without Overload: Contextual Filtering of Social Interact...
Adrien Joly
 
PPT
Réseaux Sociaux, Révolution des usages sur Internet, et nouvelles problémati...
Adrien Joly
 
PDF
Awareness Without Overload
Adrien Joly
 
PPT
Context-Awareness, the missing block of Social Networking
Adrien Joly
 
PhD Defense - A Context Management Framework based on Wisdom of Crowds for So...
Adrien Joly
 
Contextual Recommendation of Social Updates, a tag-based framework
Adrien Joly
 
Exploitation de données de contexte utilisateur pour estimer la pertinence d...
Adrien Joly
 
Tangible Contextual Tag Clouds towards Controlled and Relevant Social Inter...
Adrien Joly
 
Natural Ubiquitous Call-out
Adrien Joly
 
Workspace Awareness without Overload: Contextual Filtering of Social Interact...
Adrien Joly
 
Réseaux Sociaux, Révolution des usages sur Internet, et nouvelles problémati...
Adrien Joly
 
Awareness Without Overload
Adrien Joly
 
Context-Awareness, the missing block of Social Networking
Adrien Joly
 
Ad

Recently uploaded (20)

PDF
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
PDF
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
PDF
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
PPTX
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
PDF
Python basic programing language for automation
DanialHabibi2
 
PPTX
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
PDF
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
PDF
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PDF
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
Complete JavaScript Notes: From Basics to Advanced Concepts.pdf
haydendavispro
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PPTX
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
PDF
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
PDF
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
PDF
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
PDF
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
Python basic programing language for automation
DanialHabibi2
 
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
Complete JavaScript Notes: From Basics to Advanced Concepts.pdf
haydendavispro
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 

Introduction to asynchronous DB access using Node.js and MongoDB

  • 1. Introduction to asynchronous DB access using Node.js and MongoDB Adrien Joly [email protected]
  • 2. 1. Synchronous db query var db = DB.open("localhost:28000"); var cars = db.collection("cars"); var redCars = cars.find({color: "red"}); console.log(redCars); synchronous calls => sequential flow => simple :-)
  • 3. 2. Asynchronous db query DB.open("localhost:28000", function(err, db) { db.collection("cars", function(err, cars) { cars.find({color: "red"}, function(err, res) { console.log(res); }); }); }); asynchronous calls => callback functions
  • 4. 3. Separate view from controller (MVC) db.js (model) DB.open("localhost:28000", function(err, db) { db.collection("cars", function(err, cars) { exports.getRedCars = function(callback) { cars.query({color: "red"}, callback); }); }); }); controller.js var model = require("db"); var renderRedCars = function() { model.getRedCars(function(err, redCars) { console.log(redCars); }); };
  • 5. 4. Towards more models db.js DB.open("localhost:28000", function(err, db) { exports.getCollection = function(name, callback) { db.collection(name, callback); }; }); cars.js (model) require("db").getCollection("cars", function(err, cars) { exports.getRedCars = function(callback) { cars.query({color: "red"}, callback); }); }); }); controller.js var renderRedCars = function() { require("cars").getRedCars(function(err, redCars) { console.log(redCars); }); };
  • 6. 5. Optimization, #fail safety start_server.js (main node.js application) require("db").init(function() { // start your application (->controllers->models) here }); db.js exports.init = function (initCallback) { DB.open("localhost:28000", function(err, db) { exports.getCollection = function(name, callback) { db.collection(name, callback); }; initCallback(); }); (models and controllers) ...
  • 7. References required stuff http://nodejs.org/ http://www.mongodb.org/ https://github.com/christkv/node-mongodb-native about asynchronous DB access http://stackoverflow.com/questions/6275643/node-js-design-pattern-for-creating- db-connection-once invite to request :-p http://whyd.com/