Webinar: Building Your First App in Node.js

  • Published on
    15-Jul-2015

  • View
    118

  • Download
    2

Embed Size (px)

Transcript

<p>PowerPoint Presentation</p> <p>MongoDB + Node.jsBuilding first app with MongoDB and Node.js</p> <p>AgendaMongoDB + Node.jsDriver ODM'sMEAN StackMeteor#Ola, I'm Norberto!Norberto LeiteTechnical Evangelist </p> <p>Madrid, Spain@nleitenorberto@mongodb.comhttp://www.mongodb.com/norberto</p> <p>#MongoDB Node.js- Change this hear to a better edited one5INFACT MongoDB JavaScript- Change this hear to a better edited one7Few reasons why</p> <p>FlexibleAgileWeb Language#MongoDB + JavascriptMongoDB ShellJS interperterMongoDB MapReduceRuns on top of V8Map and Reduce functions are JS functionsNative support for Node.jsOne of the most used Drivers out there!https://www.npmjs.com/package/mongodb</p> <p>#Node.js2 Foundations</p> <p>Events</p> <p>Streams#2 FoundationsEvents / Event LoopSingle Thread ApplicationsNo threadsEvents EmitterEvent QueueKnown Events</p> <p>StreamsRead, Write, BothUnix PipesWe use it extensively!#Installnpm package$ npm install mongodbBasic Driver installation for Node.js is to follow npm repository</p> <p>14Compatibility </p> <p>http://docs.mongodb.org/ecosystem/drivers/node-js/#compatibilityCompatibility w/ MongoDB</p> <p>#Initialize Projectpackage.json file$ mkdir firstappnodejs$ cd firstappnodejs$ npm init</p> <p>We should create a project folder Initialized it with NPMAdd the dependency to MongoDB lattes version the file should resemble something very similar to the shown example18package.json file$ mkdir firstappnodejs$ cd firstappnodejs$ npm init...{ "name": "firstappnodejs", "version": "0.0.1", "description": "Small demo webinar application", "main": "index.js", "scripts": { "test": "workitout" }, "repository": { "type": "git", "url": "git://github.com/nleite/firstappnodejs" }, "dependencies": { "mongodb": "~2.0" }, "keywords": [http://docs.mongodb.org/ecosystem/drivers/node-js/#compatibility "demo", "nodejs", "mongodb" ], "author": "Norberto Leite", "license": "Apache 2.0", "bugs": { "url": "https://github.com/nleite/firstappnodejs/issues" }, "homepage": "https://github.com/nleite/firstappnodejs"}We should create a project folder Initialized it with NPMAdd the dependency to MongoDB lattes version the file should resemble something very similar to the shown example19package.json file$ mkdir firstappnodejs$ cd firstappnodejs$ npm init...{ "name": "firstappnodejs", "version": "0.0.1", "description": "Small demo webinar application", "main": "index.js", "scripts": { "test": "workitout" }, "repository": { "type": "git", "url": "git://github.com/nleite/firstappnodejs" }, "dependencies": { "mongodb": "~2.0" }, "keywords": [ "demo", "nodejs", "mongodb" ], "author": "Norberto Leite", "license": "Apache 2.0", "bugs": { "url": "https://github.com/nleite/firstappnodejs/issues" }, "homepage": "https://github.com/nleite/firstappnodejs"}- But do not forget to edit the dependencies accordingly!20Install our new firstappnodejs app!$ npm install</p> <p>&gt; kerberos@0.0.10 install &gt; bson@0.3.1 install&gt; mongodb@2.0.28 node_modules/mongodb readable-stream@1.0.31 (isarray@0.0.1, inherits@2.0.1, string_decoder@0.10.31, core-util-is@1.0.1) mongodb-core@1.1.25 (kerberos@0.0.10, bson@0.3.1)</p> <p>firstappnodejs/ $ lsnode_modules package.jsonConnectboot up MongoDB Server$ mkdir ~/firstappdb$ mongod --dbpath ~/firstappdb Raises a server listening on port 27017 by default and pointing to ~/firstappdb 23boot up MongoDB Server$ mkdir ~/firstappdb$ mongod --dbpath ~/firstappdb --auth --keyfile ~/n.pem https://www.mongodb.com/products/mongodb-enterprise-advancedDo not forget that mongodb is ready for the authentication + authorization + auditing 24boot up MongoDB Server$ mkdir ~/firstappdb$ mongod --dbpath ~/firstappdb --auth --keyfile ~/n.pem https://www.mongodb.com/products/mongodb-enterprise-advancedDon't Forget About Authentication in ProductionDo not forget that mongodb is ready for the authentication + authorization + auditing 25var MongoClient = require('mongodb').MongoClient, assert = require('assert');</p> <p>Connectvar MongoClient = require('mongodb').MongoClient, assert = require('assert');</p> <p>//connection urivar uri = "mongodb://localhost:27017/firstapp"</p> <p>Connect27var MongoClient = require('mongodb').MongoClient, assert = require('assert');</p> <p>//connection urivar uri = "mongodb://localhost:27017/firstapp"</p> <p>//connect to MongoDBMongoClient.connect(uri, function(err, db){ assert.equal(null, err); console.log("Connected correctly to server"); db.close();});</p> <p>ConnectConnection PoolingNo traditional Pooling mechanismSingle thread processSockets to pipeline operationsFailover Buffering up operations bufferMaxEntriesnumberOfRetriesretryMiliSecondshttp://mongodb.github.io/node-mongodb-native/2.0/api/Db.html#Pooling: there are no traditional concept of connection pools since this is a single threaded process. We use sockets to pupeline the commands to MongoDB.Failover consists on buffering up the commands till the servers are availableThese can be controlled by bufferMaxEntries, numberOfRetries and retryMiliSeconds</p> <p>29CRUDvar insertDocuments = function(db, cb){ //we don't need to explicitly create a collection var collection = db.collection('myCollection'); collection.insertMany([ {"mongodb": "is just awesome"}, {"nodejs": "so awesome"} ], function(err, result){ assert.equal(null, err); //inserted 2 documents assert.equal(2, result.insertedCount); //invoke callback cb(result); });}Inserthttp://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#insertvar insertDocuments = function(db, cb){ //we don't need to explicitly create a collection var collection = db.collection('myCollection'); collection.insertMany([ {"mongodb": "is just awesome"}, {"nodejs": "so awesome"} ], function(err, result){ assert.equal(null, err); //inserted 2 documents assert.equal(2, result.insertedCount); //invoke callback cb(result); });}Inserthttp://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#insertvar insertDocuments = function(db, cb){ //we don't need to explicitly create a collection var collection = db.collection('myCollection'); collection.insertMany([ {"mongodb": "is just awesome"}, {"nodejs": "so awesome"} ], function(err, result){ assert.equal(null, err); //inserted 2 documents assert.equal(2, result.insertedCount); //invoke callback cb(result); });}Inserthttp://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#insertvar insertDocuments = function(db, cb){ //we don't need to explicitly create a collection var collection = db.collection('myCollection'); collection.insertMany([ {"mongodb": "is just awesome"}, {"nodejs": "so awesome"} ], function(err, result){ assert.equal(null, err); //inserted 2 documents assert.equal(2, result.insertedCount); //invoke callback cb(result); });}Inserthttp://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#insertMongoClient.connect(uri, function(err, db) { assert.equal(null, err); console.log("Sweet! Talking to Server");</p> <p> insertDocuments(db, function() { db.close(); });});</p> <p>Inserthttp://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#insertMongoClient.connect(uri, function(err, db) { assert.equal(null, err); console.log("Sweet! Talking to Server");</p> <p> insertDocuments(db, function() { db.close(); });});</p> <p>Inserthttp://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#insertvar updateDocument = function(db, cb){ var collection = db.collection("myCollection");</p> <p> collection.updateOne( {"mongodb": "is just awesome"}, {$set: {"users": ["nleite"]}}, function( err, result){ assert.equal(null, err); assert.equal(1, result.modifiedCount);</p> <p> console.log("Cool, just updated");</p> <p> cb(result); });}</p> <p>Updatehttp://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#updatevar updateDocument = function(db, cb){ var collection = db.collection("myCollection");</p> <p> collection.updateOne( {"mongodb": "is just awesome"}, {$set: {"users": ["nleite"]}}, function( err, result){ assert.equal(null, err); assert.equal(1, result.modifiedCount);</p> <p> console.log("Cool, just updated");</p> <p> cb(result); });}</p> <p>Updatehttp://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#update- Define the query to match the wanted documents38var updateDocument = function(db, cb){ var collection = db.collection("myCollection");</p> <p> collection.updateOne( {"mongodb": "is just awesome"}, {$set: {"users": ["nleite"]}}, function( err, result){ assert.equal(null, err); assert.equal(1, result.modifiedCount);</p> <p> console.log("Cool, just updated");</p> <p> cb(result); });}</p> <p>Updatehttp://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#update$set operator that will perform the change In this case will produce the set of new array field39var updateDocument = function(db, cb){ var collection = db.collection("myCollection");</p> <p> collection.updateOne( {"mongodb": "is just awesome"}, {$set: {"users": ["nleite"]}}, function( err, result){ assert.equal(null, err); assert.equal(1, result.modifiedCount);</p> <p> console.log("Cool, just updated");</p> <p> cb(result); });}</p> <p>Updatehttp://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#updateVerify that the operation occurred without errors and matches the expected end resultIn this case 1 updated document 40MongoClient.connect(uri, function(err, db) { assert.equal(null, err); console.log("Ok, I can now update!");</p> <p> updateDocuments(db, function() { db.close(); });});</p> <p>Updatehttp://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#updateRemovevar removeDocument = function(db, cb){ var collection = db.collection("myCollection"); collection.deleteOne( {"users": "nleite"}, function( err, result){ assert.equal(null, err); assert.equal(1, result.deletedCount); console.log("purged the @nleite contaminated data!"); cb(result); });}</p> <p>http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#removeRemovevar removeDocument = function(db, cb){ var collection = db.collection("myCollection"); collection.deleteOne( {"users": "nleite"}, function( err, result){ assert.equal(null, err); assert.equal(1, result.deletedCount); console.log("purged the @nleite contaminated data!"); cb(result); });}</p> <p>http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#remove- Performs a multikey query operation43Removevar removeDocument = function(db, cb){ var collection = db.collection("myCollection"); collection.deleteOne( {"users": "nleite"}, function( err, result){ assert.equal(null, err); assert.equal(1, result.deletedCount); console.log("purged the @nleite contaminated data!"); cb(result); });}</p> <p>http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#removeRemoveMongoClient.connect(uri, function(err, db) { assert.equal(null, err); console.log("Ok, I can now delete!");</p> <p> removeDocuments(db, function() { db.close(); });});</p> <p>http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#remove</p> <p>Findvar findAllDocuments = function(db, cb){ var collection = db.collection('myDocuments'); //or collection.find() collection.find({}).toArray(function(err, docs){ assert.equal(err, null); assert.equal(1, docs.length);</p> <p> console.log("Gotcha! found "+ docs.length); console.dir(docs); cb(docs); });}</p> <p>http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findFindvar findAllDocuments = function(db, cb){ var collection = db.collection('myDocuments'); //or collection.find() collection.find({}).toArray(function(err, docs){ assert.equal(err, null); assert.equal(1, docs.length);</p> <p> console.log("Gotcha! found "+ docs.length); console.dir(docs); cb(docs); });}</p> <p>http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findFindvar findAllDocuments = function(db, cb){ var collection = db.collection('myDocuments'); //or collection.find() collection.find({}).toArray(function(err, docs){ assert.equal(err, null); assert.equal(1, docs.length);</p> <p> console.log("Gotcha! found "+ docs.length); console.dir(docs); cb(docs); });}</p> <p>http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#find- The only variation on this case is that we are not going to handle the results object but the cursor returned by the query method48FlexibilitySchema Flexibility</p> <p>Different Schemasvar insertDifferentShapes = function(db, cb){</p> <p> var doc1 = {"name": "Norberto", "talks": [ {"nodejs":10}, {"java":15}, "python":11]}; var doc2 = {"name": "Bryan", "webinars": 30};</p> <p> var coll = db.collection("content") coll.insertMany( [doc1, doc2], function(err, result){ assert.equal(err, null); assert.equal(2, result.insertedCount);</p> <p> console.log("Sweet, inserted "+ result.insertedCount); cb(result); });}http://docs.mongodb.org/manual/data-modeling/Different Schemasvar insertDifferentShapes = function(db, cb){</p> <p> var doc1 = {"name": "Norberto", "talks": [ {"nodejs":10}, {"java":15}, "python":11]}; var doc2 = {"name": "Bryan", "webinars": 30};</p> <p> var coll = db.collection("content") coll.insertMany( [doc1, doc2], function(err, result){ assert.equal(err, null); assert.equal(2, result.insertedCount);</p> <p> console.log("Sweet, inserted "+ result.insertedCount); cb(result); });}http://docs.mongodb.org/manual/data-modeling/WriteConcerns</p> <p>WriteConcern w:1</p> <p>Change this slid54WriteConcern w:2</p> <p>WriteConcern j:true</p> <p>Different WriteConcernsvar insertSuperImportant = function(db, cb){</p> <p> var customer = {"name": "Manny Delgado", "age": 14}; var coll = db.collection("customers");</p> <p> var writeConcern = {"w": "majority"};</p> <p> col.insertOne( customer, writeConcern, function(err, result){ assert.equal(err, null); assert.equal(1, result.insertedCount);</p> <p> console.log("Inserted super important record"); cb(result); });}</p> <p>http://mongodb.github.io/node-mongodb-native/2.0/api/WriteConcernError.htmlDifferent WriteConcernsvar insertSuperImportant = function(db, cb){</p> <p> var customer = {"name": "Manny Delgado", "age": 14}; var coll = db.collectio...</p>