SlideShare a Scribd company logo
1 of 43
ECMAScript 6 and the Node Driver
3
Agenda
• ES6
• ES6 Features
• MongoDB Core
• ES6 Prototype
• Performance
4
Good Evening
Christian Amor Kvalheim
Drivers Lead and Node.js driver author
Oviedo, Spain
@christkv
christkv@mongodb.com
http://www.christiankvalheim.com
ES6
6
ES6
• ES6 Is a fundamental rethink of the JavaScript language
• Introduces a lot of new features
–Iterators
–Generators
–Proxies
–Promises
–Classes
–and much more….
ES6 Features
8
Classes
• Classes are syntactic sugar on top of JavaScript existing
prototype based inheritance.
• Classes do not introduce a new Object Oriented
inheritance model.
• Classes simplify the code and provides a clearer syntax
for prototype based inheritance.
9
Classes
• ES6 Introduces classes
class Cursor {
constructor() {}
count() {}
}
10
Classes
• ES6 Introduces classes
class SpecialCursor extends Cursor {
constructor() {
super();
}
}
11
Iterators
• Iterators are created using a protocol allowing JavaScript
objects to define or customize their iteration behavior.
• Arrays in ES6 are now iterators and can be used in the
new for-of construct.
• An object is an Iterator when it implements a next()
method that returns an object with two properties.
–done (boolean)
–value (any JavaScript value)
12
Iterators
class Next {
constructor(value) { this.value = value || 0; }
}
Next.prototype[Symbol.iterator] = function() {
var cur = this.value;
return {
next() { return {done: false, value: cur++} }
}
}
for(var n of new Next()) {
if(n == 1000) break;
}
13
Promises
• A Promise is an object used for deferred and
asynchronous computations.
• A promise can either be fulfilled with a value or rejected.
• Promises can be chained using then.
• Execute n promises using Promise.all.
• Very useful to orchestrate asynchronous operations.
• Allows for easier reasoning of call chains.
14
Promises
var p2 = new Promise(function(resolve, reject) {
resolve(2);
});
p2.then(function(value) {
assert(2, value);
});
var promise = Promise.resolve(3);
Promise.all([true, promise])
.then(function(values) {
console.log(values);
});
15
Generators
• A Generator is a function that can be exited, and then
later re-entered.
• The context of the function is saved across re-entrances.
• Calling a Generator function returns an iterator object.
• Calling next on the iterator executes the function until the
first yield is encountered.
16
Generators
class Next {
constructor(value) { this.value = value || 0; }
}
Next.prototype[Symbol.iterator] = function*() {
var cur = this.value;
while(true) {
yield cur++;
}
}
for(var n of new Next()) {
if(n == 1000) break;
}
17
Generators + co
• co library
–Runs a generator to the end
–Expects to yield on promises
–Simplifies the syntax for programming
18
Generators + co
var co = require('co'),
assert = require('assert');
var p1 = new Promise(function(resolve, reject) {
resolve(2);
});
co(function*() {
var value = yield p1;
assert.equal(2, value);
}).catch(function(err) {
console.dir(err)
});
19
Proxies
• Proxies allows a user to override fundamental behaviors
of an object
–Property lookup
–Assignment
–Function calls
–Enumeration
• Proxies is close to method_missing in ruby.
• Proxies can lead to slow execution if in critical code path.
20
Proxies
var handler = {
get: function(target, name){
return name in target ? target[name] : 37;
}
};
var p = new Proxy({}, handler);
p.a = 1;
p.b = undefined;
console.log(p.a, p.b); // 1, undefined
console.log('c' in p, p.c); // false, 37
MongoDB Core
22
MongoDB Core
• MongoDB Core is a low level driver wrapping the wire
protocol and authentication
–No abstractions
• MongoDB Core was developed to allow for people to
more easily write
–ODMs (Object Document Modeling)
–Driver Wrappers
–Tools/Frameworks
23
Simple Example
var Server = require('mongodb-core').Server;
// Attempt to connect
var server = new Server({ host: 'localhost', port: 27017 })
// Add event listeners
server.on('connect', function(server) {
// Execute the command
server.command("system.$cmd"
, {ismaster: true}, function(err, result) {
server.destroy();
});
});
server.connect();
24
Mongodb-core
• install
npm install mongodb-core
• Tested on
–Node 12.2
–IO.js 2.0
• https://github.com/christkv/mongodb-core
ES6 Prototype
26
ES6 Prototype
• Prototype aims to explore the ES6 space to improve the
usability of the driver.
–Leverage only the features of ES6 that improves
productivity
–Ensure no significant performance degradation
happens in the transition from ES5 to ES6
27
FROM
var MongoClient = require(‘mongodb’).MongoClient,
assert = require(‘assert’);
MongoClient.connect(‘mongodb://localhost:27017/test’
, function(e, d) {
assert.equal(null, e);
var c = d.collection(‘test1’);
c.insertOne({a:1}, function(e, r) {
assert.equal(null, e);
c.find({}).toArray(function(e, docs) {
assert.equal(null, e);
assert.equal(1, docs.length);
d.close();
});
});
});
28
TO
var MongoClient = require(’mongodb-es6').MongoClient,
co = require(‘co’);
co(function* () {
var client = yield new
MongoClient('mongodb://localhost:27017/test', {}).connect()
try {
var result = yield client['tests']['cursors'].insertOne({a:2});
} catch(err) {};
var docs = yield client['tests']['cursors'].find({}).toArray();
}).catch(function(err) {
console.dir(err)
});
29
ES6 Driver Design
• Driver uses MongoDB Core as it’s bases.
• Driver leverages the following features of ES6
– Classes
– Promises
• Forward compatible with co
• Forward compatible with ES7 async/await
– Proxies
30
Classes
• Prototype has classes for
– Db
– Collection
– Cursor
– AggregationCursor
– CommandCursor
– MongoClient
• Prototype has a minimal API
31
Promises
• Prototype returns a Promise for all asynchronous
methods, no callbacks.
command(cmd) {
var self = this;
return new this.options.promise(function(resolve, reject) {
self.topology.command(f('%s.$cmd', self.name), cmd,
function(err, r) {
if(err) reject(err);
else resolve(r);
});
});
}
32
Promises
• Prototype returns standard ES6 promises
• Bring Your Own Promises (BYOP)
var MongoClient = require(’mongodb-es6').MongoClient
, P = require("bluebird");
co(function* () {
var client = yield new MongoClient('mongodb://localhost:27017/test’)
.promiseLibrary(P).connect();
});
33
Promises + Iteration
• Iterating a cursor is completely different from 2.x
var MongoClient = require(’mongodb-es6').MongoClient
, P = require("bluebird");
co(function* () {
var client = yield new MongoClient('mongodb://localhost:27017/test’)
.promiseLibrary(P).connect();
var cursor = client[‘tests’][‘docs’].find({});
while(yield cursor.hasNext()) {
console.dir(yield cursor.next());
}
}).catch(function(err) {
console.dir(err);
});
34
Proxies
• Prototype uses proxies to allow for simpler access to
databases allowing you to do.
var MongoClient = require(’mongodb-es6').MongoClient,
co = require(‘co’);
co(function* () {
var client = yield new
MongoClient('mongodb://localhost:27017/test', {}).connect();
var testsDb = yield client['tests’];
var cursorsCollection = yield testsDb['cursors’]
}).catch(function(err) {
console.dir(err)
});
35
Proxies Gotchas
• Proxies come with some performance implications.
• Proxies are inherently poison to the way V8 JITs into
stable classes as a proxy wrapped instance can be x
possible classes forcing de-optimizations.
for(var i = 0; i < 10; i++) {
yield client[‘tests’][‘docs’].insertOne({a:1});
}
var col = client[‘tests’][‘docs’];
for(var i = 0; i < 10; i++) {
yield col.insertOne({a:1})
}
Performance
37
Performance
2.0 (IO 2.0) simple_100_document_toArray
Average 0.414 ms
Standard Deviation 0.498 ms
ES6 (IO 2.0) simple_100_document_toArray
Average 0.415 ms
Standard Deviation 0.501 ms
Release Information
39
Release Information
• Prototype install
npm install mongodb-es6
• Tested on
–Node 12.2
–IO.js 2.0
• https://github.com/christkv/mongodb-es6
One
More
Thing
41
2.1- alpha with Promises
• 2.1- alpha install
npm install mongodb@2.1-alpha
• https://github.com/mongodb/node-mongodb-native
42
Simple 2.1-alpha Example
var MongoClient = require(’mongodb'),
Promise = require('bluebird');
MongoClient.connect(configuration.url(), {
promiseLibrary: Promise
}).then(function(db) {
var promise = db.collection('test').insert({a:1});
test.ok(promise instanceof Promise);
promise.then(function() {
db.close();
test.done();
});
});
ECMAScript 6 and the Node Driver

More Related Content

What's hot

Node js presentation
Node js presentationNode js presentation
Node js presentation
martincabrera
 
Using Node.js to Build Great Streaming Services - HTML5 Dev Conf
Using Node.js to  Build Great  Streaming Services - HTML5 Dev ConfUsing Node.js to  Build Great  Streaming Services - HTML5 Dev Conf
Using Node.js to Build Great Streaming Services - HTML5 Dev Conf
Tom Croucher
 
Mobile webapplication development
Mobile webapplication developmentMobile webapplication development
Mobile webapplication development
Ganesh Gembali
 
Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}
.toster
 
Psgi Plack Sfpm
Psgi Plack SfpmPsgi Plack Sfpm
Psgi Plack Sfpm
som_nangia
 
Ruby on Rails Oracle adaptera izstrāde
Ruby on Rails Oracle adaptera izstrādeRuby on Rails Oracle adaptera izstrāde
Ruby on Rails Oracle adaptera izstrāde
Raimonds Simanovskis
 

What's hot (20)

Node js presentation
Node js presentationNode js presentation
Node js presentation
 
Talk KVO with rac by Philippe Converset
Talk KVO with rac by Philippe ConversetTalk KVO with rac by Philippe Converset
Talk KVO with rac by Philippe Converset
 
Node.js - Best practices
Node.js  - Best practicesNode.js  - Best practices
Node.js - Best practices
 
Using Node.js to Build Great Streaming Services - HTML5 Dev Conf
Using Node.js to  Build Great  Streaming Services - HTML5 Dev ConfUsing Node.js to  Build Great  Streaming Services - HTML5 Dev Conf
Using Node.js to Build Great Streaming Services - HTML5 Dev Conf
 
Mobile webapplication development
Mobile webapplication developmentMobile webapplication development
Mobile webapplication development
 
node.js dao
node.js daonode.js dao
node.js dao
 
Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}
 
Node.js - A Quick Tour
Node.js - A Quick TourNode.js - A Quick Tour
Node.js - A Quick Tour
 
mruby で mackerel のプラグインを作るはなし
mruby で mackerel のプラグインを作るはなしmruby で mackerel のプラグインを作るはなし
mruby で mackerel のプラグインを作るはなし
 
FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6
 
Map kit light
Map kit lightMap kit light
Map kit light
 
JS everywhere 2011
JS everywhere 2011JS everywhere 2011
JS everywhere 2011
 
Javascript Everywhere From Nose To Tail
Javascript Everywhere From Nose To TailJavascript Everywhere From Nose To Tail
Javascript Everywhere From Nose To Tail
 
ECMAScript 6: A Better JavaScript for the Ambient Computing Era
ECMAScript 6: A Better JavaScript for the Ambient Computing EraECMAScript 6: A Better JavaScript for the Ambient Computing Era
ECMAScript 6: A Better JavaScript for the Ambient Computing Era
 
Introduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoaIntroduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoa
 
Psgi Plack Sfpm
Psgi Plack SfpmPsgi Plack Sfpm
Psgi Plack Sfpm
 
Nodejs intro
Nodejs introNodejs intro
Nodejs intro
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.js
 
Node.js Patterns for Discerning Developers
Node.js Patterns for Discerning DevelopersNode.js Patterns for Discerning Developers
Node.js Patterns for Discerning Developers
 
Ruby on Rails Oracle adaptera izstrāde
Ruby on Rails Oracle adaptera izstrādeRuby on Rails Oracle adaptera izstrāde
Ruby on Rails Oracle adaptera izstrāde
 

Viewers also liked

Viewers also liked (6)

JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
Utilizing Bluebird Promises
Utilizing Bluebird PromisesUtilizing Bluebird Promises
Utilizing Bluebird Promises
 
Promise and Bluebird
Promise and BluebirdPromise and Bluebird
Promise and Bluebird
 
ES2015 / ES6: Basics of modern Javascript
ES2015 / ES6: Basics of modern JavascriptES2015 / ES6: Basics of modern Javascript
ES2015 / ES6: Basics of modern Javascript
 
ES2015 (ES6) Overview
ES2015 (ES6) OverviewES2015 (ES6) Overview
ES2015 (ES6) Overview
 
Webinar: 10-Step Guide to Creating a Single View of your Business
Webinar: 10-Step Guide to Creating a Single View of your BusinessWebinar: 10-Step Guide to Creating a Single View of your Business
Webinar: 10-Step Guide to Creating a Single View of your Business
 

Similar to ECMAScript 6 and the Node Driver

JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
David Padbury
 
The Architecture of PicCollage Server
The Architecture of PicCollage ServerThe Architecture of PicCollage Server
The Architecture of PicCollage Server
Lin Jen-Shin
 

Similar to ECMAScript 6 and the Node Driver (20)

Introduction to REST API with Node.js
Introduction to REST API with Node.jsIntroduction to REST API with Node.js
Introduction to REST API with Node.js
 
Dragoncraft Architectural Overview
Dragoncraft Architectural OverviewDragoncraft Architectural Overview
Dragoncraft Architectural Overview
 
Top 10 RxJs Operators in Angular
Top 10 RxJs Operators in Angular Top 10 RxJs Operators in Angular
Top 10 RxJs Operators in Angular
 
From Zero To Production (NixOS, Erlang) @ Erlang Factory SF 2016
From Zero To Production (NixOS, Erlang) @ Erlang Factory SF 2016From Zero To Production (NixOS, Erlang) @ Erlang Factory SF 2016
From Zero To Production (NixOS, Erlang) @ Erlang Factory SF 2016
 
From development environments to production deployments with Docker, Compose,...
From development environments to production deployments with Docker, Compose,...From development environments to production deployments with Docker, Compose,...
From development environments to production deployments with Docker, Compose,...
 
Spark SQL Catalyst Code Optimization using Function Outlining with Kavana Bha...
Spark SQL Catalyst Code Optimization using Function Outlining with Kavana Bha...Spark SQL Catalyst Code Optimization using Function Outlining with Kavana Bha...
Spark SQL Catalyst Code Optimization using Function Outlining with Kavana Bha...
 
Everything as a Code / Александр Тарасов (Одноклассники)
Everything as a Code / Александр Тарасов (Одноклассники)Everything as a Code / Александр Тарасов (Одноклассники)
Everything as a Code / Александр Тарасов (Одноклассники)
 
Everything as a code
Everything as a codeEverything as a code
Everything as a code
 
React Development with the MERN Stack
React Development with the MERN StackReact Development with the MERN Stack
React Development with the MERN Stack
 
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
Building and Scaling Node.js Applications
Building and Scaling Node.js ApplicationsBuilding and Scaling Node.js Applications
Building and Scaling Node.js Applications
 
Node azure
Node azureNode azure
Node azure
 
Introducing the Seneca MVP framework for Node.js
Introducing the Seneca MVP framework for Node.jsIntroducing the Seneca MVP framework for Node.js
Introducing the Seneca MVP framework for Node.js
 
20120816 nodejsdublin
20120816 nodejsdublin20120816 nodejsdublin
20120816 nodejsdublin
 
Building High Perf Web Apps - IE8 Firestarter
Building High Perf Web Apps - IE8 FirestarterBuilding High Perf Web Apps - IE8 Firestarter
Building High Perf Web Apps - IE8 Firestarter
 
C sharp 8.0 new features
C sharp 8.0 new featuresC sharp 8.0 new features
C sharp 8.0 new features
 
C sharp 8.0 new features
C sharp 8.0 new featuresC sharp 8.0 new features
C sharp 8.0 new features
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
The Architecture of PicCollage Server
The Architecture of PicCollage ServerThe Architecture of PicCollage Server
The Architecture of PicCollage Server
 

More from MongoDB

More from MongoDB (20)

MongoDB SoCal 2020: Migrate Anything* to MongoDB Atlas
MongoDB SoCal 2020: Migrate Anything* to MongoDB AtlasMongoDB SoCal 2020: Migrate Anything* to MongoDB Atlas
MongoDB SoCal 2020: Migrate Anything* to MongoDB Atlas
 
MongoDB SoCal 2020: Go on a Data Safari with MongoDB Charts!
MongoDB SoCal 2020: Go on a Data Safari with MongoDB Charts!MongoDB SoCal 2020: Go on a Data Safari with MongoDB Charts!
MongoDB SoCal 2020: Go on a Data Safari with MongoDB Charts!
 
MongoDB SoCal 2020: Using MongoDB Services in Kubernetes: Any Platform, Devel...
MongoDB SoCal 2020: Using MongoDB Services in Kubernetes: Any Platform, Devel...MongoDB SoCal 2020: Using MongoDB Services in Kubernetes: Any Platform, Devel...
MongoDB SoCal 2020: Using MongoDB Services in Kubernetes: Any Platform, Devel...
 
MongoDB SoCal 2020: A Complete Methodology of Data Modeling for MongoDB
MongoDB SoCal 2020: A Complete Methodology of Data Modeling for MongoDBMongoDB SoCal 2020: A Complete Methodology of Data Modeling for MongoDB
MongoDB SoCal 2020: A Complete Methodology of Data Modeling for MongoDB
 
MongoDB SoCal 2020: From Pharmacist to Analyst: Leveraging MongoDB for Real-T...
MongoDB SoCal 2020: From Pharmacist to Analyst: Leveraging MongoDB for Real-T...MongoDB SoCal 2020: From Pharmacist to Analyst: Leveraging MongoDB for Real-T...
MongoDB SoCal 2020: From Pharmacist to Analyst: Leveraging MongoDB for Real-T...
 
MongoDB SoCal 2020: Best Practices for Working with IoT and Time-series Data
MongoDB SoCal 2020: Best Practices for Working with IoT and Time-series DataMongoDB SoCal 2020: Best Practices for Working with IoT and Time-series Data
MongoDB SoCal 2020: Best Practices for Working with IoT and Time-series Data
 
MongoDB SoCal 2020: MongoDB Atlas Jump Start
 MongoDB SoCal 2020: MongoDB Atlas Jump Start MongoDB SoCal 2020: MongoDB Atlas Jump Start
MongoDB SoCal 2020: MongoDB Atlas Jump Start
 
MongoDB .local San Francisco 2020: Powering the new age data demands [Infosys]
MongoDB .local San Francisco 2020: Powering the new age data demands [Infosys]MongoDB .local San Francisco 2020: Powering the new age data demands [Infosys]
MongoDB .local San Francisco 2020: Powering the new age data demands [Infosys]
 
MongoDB .local San Francisco 2020: Using Client Side Encryption in MongoDB 4.2
MongoDB .local San Francisco 2020: Using Client Side Encryption in MongoDB 4.2MongoDB .local San Francisco 2020: Using Client Side Encryption in MongoDB 4.2
MongoDB .local San Francisco 2020: Using Client Side Encryption in MongoDB 4.2
 
MongoDB .local San Francisco 2020: Using MongoDB Services in Kubernetes: any ...
MongoDB .local San Francisco 2020: Using MongoDB Services in Kubernetes: any ...MongoDB .local San Francisco 2020: Using MongoDB Services in Kubernetes: any ...
MongoDB .local San Francisco 2020: Using MongoDB Services in Kubernetes: any ...
 
MongoDB .local San Francisco 2020: Go on a Data Safari with MongoDB Charts!
MongoDB .local San Francisco 2020: Go on a Data Safari with MongoDB Charts!MongoDB .local San Francisco 2020: Go on a Data Safari with MongoDB Charts!
MongoDB .local San Francisco 2020: Go on a Data Safari with MongoDB Charts!
 
MongoDB .local San Francisco 2020: From SQL to NoSQL -- Changing Your Mindset
MongoDB .local San Francisco 2020: From SQL to NoSQL -- Changing Your MindsetMongoDB .local San Francisco 2020: From SQL to NoSQL -- Changing Your Mindset
MongoDB .local San Francisco 2020: From SQL to NoSQL -- Changing Your Mindset
 
MongoDB .local San Francisco 2020: MongoDB Atlas Jumpstart
MongoDB .local San Francisco 2020: MongoDB Atlas JumpstartMongoDB .local San Francisco 2020: MongoDB Atlas Jumpstart
MongoDB .local San Francisco 2020: MongoDB Atlas Jumpstart
 
MongoDB .local San Francisco 2020: Tips and Tricks++ for Querying and Indexin...
MongoDB .local San Francisco 2020: Tips and Tricks++ for Querying and Indexin...MongoDB .local San Francisco 2020: Tips and Tricks++ for Querying and Indexin...
MongoDB .local San Francisco 2020: Tips and Tricks++ for Querying and Indexin...
 
MongoDB .local San Francisco 2020: Aggregation Pipeline Power++
MongoDB .local San Francisco 2020: Aggregation Pipeline Power++MongoDB .local San Francisco 2020: Aggregation Pipeline Power++
MongoDB .local San Francisco 2020: Aggregation Pipeline Power++
 
MongoDB .local San Francisco 2020: A Complete Methodology of Data Modeling fo...
MongoDB .local San Francisco 2020: A Complete Methodology of Data Modeling fo...MongoDB .local San Francisco 2020: A Complete Methodology of Data Modeling fo...
MongoDB .local San Francisco 2020: A Complete Methodology of Data Modeling fo...
 
MongoDB .local San Francisco 2020: MongoDB Atlas Data Lake Technical Deep Dive
MongoDB .local San Francisco 2020: MongoDB Atlas Data Lake Technical Deep DiveMongoDB .local San Francisco 2020: MongoDB Atlas Data Lake Technical Deep Dive
MongoDB .local San Francisco 2020: MongoDB Atlas Data Lake Technical Deep Dive
 
MongoDB .local San Francisco 2020: Developing Alexa Skills with MongoDB & Golang
MongoDB .local San Francisco 2020: Developing Alexa Skills with MongoDB & GolangMongoDB .local San Francisco 2020: Developing Alexa Skills with MongoDB & Golang
MongoDB .local San Francisco 2020: Developing Alexa Skills with MongoDB & Golang
 
MongoDB .local Paris 2020: Realm : l'ingrédient secret pour de meilleures app...
MongoDB .local Paris 2020: Realm : l'ingrédient secret pour de meilleures app...MongoDB .local Paris 2020: Realm : l'ingrédient secret pour de meilleures app...
MongoDB .local Paris 2020: Realm : l'ingrédient secret pour de meilleures app...
 
MongoDB .local Paris 2020: Upply @MongoDB : Upply : Quand le Machine Learning...
MongoDB .local Paris 2020: Upply @MongoDB : Upply : Quand le Machine Learning...MongoDB .local Paris 2020: Upply @MongoDB : Upply : Quand le Machine Learning...
MongoDB .local Paris 2020: Upply @MongoDB : Upply : Quand le Machine Learning...
 

Recently uploaded

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Recently uploaded (20)

Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 

ECMAScript 6 and the Node Driver

  • 1.
  • 2. ECMAScript 6 and the Node Driver
  • 3. 3 Agenda • ES6 • ES6 Features • MongoDB Core • ES6 Prototype • Performance
  • 4. 4 Good Evening Christian Amor Kvalheim Drivers Lead and Node.js driver author Oviedo, Spain @christkv christkv@mongodb.com http://www.christiankvalheim.com
  • 5. ES6
  • 6. 6 ES6 • ES6 Is a fundamental rethink of the JavaScript language • Introduces a lot of new features –Iterators –Generators –Proxies –Promises –Classes –and much more….
  • 8. 8 Classes • Classes are syntactic sugar on top of JavaScript existing prototype based inheritance. • Classes do not introduce a new Object Oriented inheritance model. • Classes simplify the code and provides a clearer syntax for prototype based inheritance.
  • 9. 9 Classes • ES6 Introduces classes class Cursor { constructor() {} count() {} }
  • 10. 10 Classes • ES6 Introduces classes class SpecialCursor extends Cursor { constructor() { super(); } }
  • 11. 11 Iterators • Iterators are created using a protocol allowing JavaScript objects to define or customize their iteration behavior. • Arrays in ES6 are now iterators and can be used in the new for-of construct. • An object is an Iterator when it implements a next() method that returns an object with two properties. –done (boolean) –value (any JavaScript value)
  • 12. 12 Iterators class Next { constructor(value) { this.value = value || 0; } } Next.prototype[Symbol.iterator] = function() { var cur = this.value; return { next() { return {done: false, value: cur++} } } } for(var n of new Next()) { if(n == 1000) break; }
  • 13. 13 Promises • A Promise is an object used for deferred and asynchronous computations. • A promise can either be fulfilled with a value or rejected. • Promises can be chained using then. • Execute n promises using Promise.all. • Very useful to orchestrate asynchronous operations. • Allows for easier reasoning of call chains.
  • 14. 14 Promises var p2 = new Promise(function(resolve, reject) { resolve(2); }); p2.then(function(value) { assert(2, value); }); var promise = Promise.resolve(3); Promise.all([true, promise]) .then(function(values) { console.log(values); });
  • 15. 15 Generators • A Generator is a function that can be exited, and then later re-entered. • The context of the function is saved across re-entrances. • Calling a Generator function returns an iterator object. • Calling next on the iterator executes the function until the first yield is encountered.
  • 16. 16 Generators class Next { constructor(value) { this.value = value || 0; } } Next.prototype[Symbol.iterator] = function*() { var cur = this.value; while(true) { yield cur++; } } for(var n of new Next()) { if(n == 1000) break; }
  • 17. 17 Generators + co • co library –Runs a generator to the end –Expects to yield on promises –Simplifies the syntax for programming
  • 18. 18 Generators + co var co = require('co'), assert = require('assert'); var p1 = new Promise(function(resolve, reject) { resolve(2); }); co(function*() { var value = yield p1; assert.equal(2, value); }).catch(function(err) { console.dir(err) });
  • 19. 19 Proxies • Proxies allows a user to override fundamental behaviors of an object –Property lookup –Assignment –Function calls –Enumeration • Proxies is close to method_missing in ruby. • Proxies can lead to slow execution if in critical code path.
  • 20. 20 Proxies var handler = { get: function(target, name){ return name in target ? target[name] : 37; } }; var p = new Proxy({}, handler); p.a = 1; p.b = undefined; console.log(p.a, p.b); // 1, undefined console.log('c' in p, p.c); // false, 37
  • 22. 22 MongoDB Core • MongoDB Core is a low level driver wrapping the wire protocol and authentication –No abstractions • MongoDB Core was developed to allow for people to more easily write –ODMs (Object Document Modeling) –Driver Wrappers –Tools/Frameworks
  • 23. 23 Simple Example var Server = require('mongodb-core').Server; // Attempt to connect var server = new Server({ host: 'localhost', port: 27017 }) // Add event listeners server.on('connect', function(server) { // Execute the command server.command("system.$cmd" , {ismaster: true}, function(err, result) { server.destroy(); }); }); server.connect();
  • 24. 24 Mongodb-core • install npm install mongodb-core • Tested on –Node 12.2 –IO.js 2.0 • https://github.com/christkv/mongodb-core
  • 26. 26 ES6 Prototype • Prototype aims to explore the ES6 space to improve the usability of the driver. –Leverage only the features of ES6 that improves productivity –Ensure no significant performance degradation happens in the transition from ES5 to ES6
  • 27. 27 FROM var MongoClient = require(‘mongodb’).MongoClient, assert = require(‘assert’); MongoClient.connect(‘mongodb://localhost:27017/test’ , function(e, d) { assert.equal(null, e); var c = d.collection(‘test1’); c.insertOne({a:1}, function(e, r) { assert.equal(null, e); c.find({}).toArray(function(e, docs) { assert.equal(null, e); assert.equal(1, docs.length); d.close(); }); }); });
  • 28. 28 TO var MongoClient = require(’mongodb-es6').MongoClient, co = require(‘co’); co(function* () { var client = yield new MongoClient('mongodb://localhost:27017/test', {}).connect() try { var result = yield client['tests']['cursors'].insertOne({a:2}); } catch(err) {}; var docs = yield client['tests']['cursors'].find({}).toArray(); }).catch(function(err) { console.dir(err) });
  • 29. 29 ES6 Driver Design • Driver uses MongoDB Core as it’s bases. • Driver leverages the following features of ES6 – Classes – Promises • Forward compatible with co • Forward compatible with ES7 async/await – Proxies
  • 30. 30 Classes • Prototype has classes for – Db – Collection – Cursor – AggregationCursor – CommandCursor – MongoClient • Prototype has a minimal API
  • 31. 31 Promises • Prototype returns a Promise for all asynchronous methods, no callbacks. command(cmd) { var self = this; return new this.options.promise(function(resolve, reject) { self.topology.command(f('%s.$cmd', self.name), cmd, function(err, r) { if(err) reject(err); else resolve(r); }); }); }
  • 32. 32 Promises • Prototype returns standard ES6 promises • Bring Your Own Promises (BYOP) var MongoClient = require(’mongodb-es6').MongoClient , P = require("bluebird"); co(function* () { var client = yield new MongoClient('mongodb://localhost:27017/test’) .promiseLibrary(P).connect(); });
  • 33. 33 Promises + Iteration • Iterating a cursor is completely different from 2.x var MongoClient = require(’mongodb-es6').MongoClient , P = require("bluebird"); co(function* () { var client = yield new MongoClient('mongodb://localhost:27017/test’) .promiseLibrary(P).connect(); var cursor = client[‘tests’][‘docs’].find({}); while(yield cursor.hasNext()) { console.dir(yield cursor.next()); } }).catch(function(err) { console.dir(err); });
  • 34. 34 Proxies • Prototype uses proxies to allow for simpler access to databases allowing you to do. var MongoClient = require(’mongodb-es6').MongoClient, co = require(‘co’); co(function* () { var client = yield new MongoClient('mongodb://localhost:27017/test', {}).connect(); var testsDb = yield client['tests’]; var cursorsCollection = yield testsDb['cursors’] }).catch(function(err) { console.dir(err) });
  • 35. 35 Proxies Gotchas • Proxies come with some performance implications. • Proxies are inherently poison to the way V8 JITs into stable classes as a proxy wrapped instance can be x possible classes forcing de-optimizations. for(var i = 0; i < 10; i++) { yield client[‘tests’][‘docs’].insertOne({a:1}); } var col = client[‘tests’][‘docs’]; for(var i = 0; i < 10; i++) { yield col.insertOne({a:1}) }
  • 37. 37 Performance 2.0 (IO 2.0) simple_100_document_toArray Average 0.414 ms Standard Deviation 0.498 ms ES6 (IO 2.0) simple_100_document_toArray Average 0.415 ms Standard Deviation 0.501 ms
  • 39. 39 Release Information • Prototype install npm install mongodb-es6 • Tested on –Node 12.2 –IO.js 2.0 • https://github.com/christkv/mongodb-es6
  • 41. 41 2.1- alpha with Promises • 2.1- alpha install npm install mongodb@2.1-alpha • https://github.com/mongodb/node-mongodb-native
  • 42. 42 Simple 2.1-alpha Example var MongoClient = require(’mongodb'), Promise = require('bluebird'); MongoClient.connect(configuration.url(), { promiseLibrary: Promise }).then(function(db) { var promise = db.collection('test').insert({a:1}); test.ok(promise instanceof Promise); promise.then(function() { db.close(); test.done(); }); });

Editor's Notes

  1. Iterators are synchronous
  2. Iterators are synchronous