Node.js Crash Course Haim Michael October 4th , 2018 All logos, trade marks and brand names used in this presentation belong to the respective owners. lifemichael Part 1: https://youtu.be/fnwdm4yob2o Part 2: https://youtu.be/OWCDm5_RbRQ
© 1996-2018 All Rights Reserved. Haim Michael Introduction ● Snowboarding. Learning. Coding. Teaching. More than 18 years of Practical Experience. lifemichael
© 1996-2018 All Rights Reserved. Haim Michael Introduction ● Professional Certifications Zend Certified Engineer in PHP Certified Java Professional Certified Java EE Web Component Developer OMG Certified UML Professional ● MBA (cum laude) from Tel-Aviv University Information Systems Management lifemichael
© 2008 Haim Michael 20150805 Introduction
10/04/18 © abelski 5 What is Node.js?  The node.js platform allows us to execute code in JavaScript outside of the web browser, which allows us to use this platform for developing web applications excellent in their performance.  The node.js platform is based on JavaScript v8. We use the JavaScript language.
10/04/18 © abelski 6 Asynchronous Programming  Most of the functions in node.js are asynchronous ones. As a result of that everything is executed in the background (instead of blocking the thread).
10/04/18 © abelski 7 The Module Architecture  The node.js platform uses the module architecture. It simplifies the creation of complex applications.  Each module contains a set of related functions.  We use the require() function in order to include a module we want to use.
10/04/18 © abelski 8 We Do Everything  The node.js platform is the environment. It doesn't include any default HTTP server.
10/04/18 © abelski 9 Installing Node  Installing node.js on your desktop is very simple. You just need to download the installation file and execute it. www.nodejs.org
10/04/18 © abelski 10 Installing Node
10/04/18 © abelski 11 The node.js CLI  Once node.js is installed on your desktop you can easy start using its CLI. Just open the terminal and type node for getting the CLI.
10/04/18 © abelski 12 The node.js CLI
10/04/18 © abelski 13 Executing JavaScript Files  Using node.js CLI we can execute files that include code in JavaScript. We just need to type node following with the name of the file.
10/04/18 © abelski 14 Executing JavaScript Files
10/04/18 © abelski 15 Node Package Manager  The Node Package Manager, AKA as NPM, allows us to manage the packages installed on our computer.  NPM provides us with an online public registry service that contains all the packages programmers publish using the NPM.  The NPM provides us with a tool we can use for downloading, installing the managing those packages.
10/04/18 © abelski 16 Node Package Manager  As of Node.js 6 the NPM is installed as part of the node.js installation.  The centralized repository of public modules that NPM maintains is available for browsing at http://npmjs.org.
10/04/18 © abelski 17 Node Package Manager
10/04/18 © abelski 18 The npm Utility  There are two modes for using the node.js package manager, also known as npm.  The local mode is the default one. In order to be in the global mode we should add the -g flag when using the npm command.
10/04/18 © abelski 19 The npm Utility  Using npm in the local mode means that we get a copy of the module on our desktop saved in a subfolder within our current folder.  Using npm in the global mode the module file will be saved together with all other modules that were fetched globally inside /usr/local/lib/node_modules/.
10/04/18 © abelski 20 The npm Utility  Let's assume we want to use the facebook module from the npm repository. Typing npm install facebook will download and install the facebook module into our platform so from now on we will be able to use it.
10/04/18 © abelski 21 The npm Utility
10/04/18 © abelski 22 Running HTTP Server on Our Desktop  We can easily set up on our desktop an up and running HTTP server that runs a web application developed in node.js.  We just need to write our code in a separated JavaScript file and execute it.
10/04/18 © abelski 23 Running HTTP Server on Our Desktop var http = require('http'); var server = http.createServer(function (req, res) { res.writeHead(200, {'Content-Type':'text/plain'}); res.end('Hello World!n'); }); server.listen(1400,'127.0.0.1');
10/04/18 © abelski 24 Running HTTP Server on Our Desktop
© 2008 Haim Michael 20150805 Query String
10/04/18 © abelski 26 Accessing The Query String  The url module allows us to access the query string. Calling the parse method on the url module passing over req.url as the first argument and true as the second one will get us an object that its properties are the parameters the query string includes. The keys are the parameters names. The values are their values.
10/04/18 © abelski 27 Accessing The Query String var http = require('http'); var url = require('url') ; http.createServer(function (req, res) { //var area = req.query.width * req.query.height; res.writeHead(200, {'Content-Type': 'text/plain'}); var queryObject = url.parse(req.url,true).query; res.end('area is '+(queryObject.width*queryObject.height)); }).listen(1400, function(){console.log("listening in port 1400");});
© 2008 Haim Michael 20150805 Event Loop
10/04/18 © abelski 29 The Loop  When Node.js starts, it first initializes the event loop and then it starts with processing the input script.
10/04/18 © abelski 30 The Loop  timers This phase executes callbacks scheduled by setTimeout() and setInterval().  pending callbacks This phase executes I/O callbacks deferred to the next loop iteration.  idle, prepare This phase is been used internally only.
10/04/18 © abelski 31 The Loop  poll This phase retrieves new I/O events; execute I/O related callbacks (almost all with the exception of close callbacks, the ones scheduled by timers, and setImmediate()); node will block here when appropriate.  check This phase includes the invocation of setImmediate() callbacks
10/04/18 © abelski 32 The Loop  close This phase is responsible for the invocation of close callbacks (e.g. socket.on('close', …);).
© 2008 Haim Michael 20150805 MongoDB
© 2008 Haim Michael What is MongoDB?  MongoDB is a flexible and a scalable document oriented database that supports most of the useful features relational databases have.
© 2008 Haim Michael Document Oriented Database  The document concept is more flexible comparing with the row concept we all know from relational databases. The document model allows us to represent hierarchical relationships with a single record.
© 2008 Haim Michael Flexibility  Using MongoDB we don't need to set a schema. The document's keys don't need to be predefined or fixed. This feature allows us an easy migration of our application into other platforms.
© 2008 Haim Michael Scaling  When the amount of data grows there is a need in scaling up (getting a stronger hardware) our data store or scaling out (partition the data across more computers). MongoDB document oriented data model allows us to automatically split up the data across multiple servers. MongoDB handles most of this process automatically.
© 2008 Haim Michael Stored JavaScript  MongoDB allows us to use JavaScript functions as stored procedures.
© 2008 Haim Michael Speed  MongoDB uses a binary wire protocol as its primary mode of interaction with the server, while other databases usually use heavy protocols such as HTTP/REST.  In order to achieve high performance many of the well known features from relational databases were taken away.
© 2008 Haim Michael Simple Administration  In order to keep the MongoDB easy and simple to use its administration was simplified and is much simpler comparing with other databases.  When the master server goes down MongoDB automatically failover to a backup slave and promote the slave to be the master.
© 2008 Haim Michael Documents  Document is a set of keys with associated values, such as a map.  In JavaScript a document is represented as an object. {“lecture“:“Haim Michael“, “topic“:“Scala Course“, “id“: 2345335321}  The values a document holds can be of different types. They can even be other documents. key value key value key value
© 2008 Haim Michael The Keys  We cannot contain duplicate keys within the same document.  The keys are strings. These strings can include any UTF-8 character.  The '0' character cannot be part of a key. This character is in use for separating keys from their values.  The '.' and the '$' characters have a special meaning (explained later).
© 2008 Haim Michael The Keys  Keys that start with '_' are considered reserved keys. We should avoid creating keys that start with this character.
© 2008 Haim Michael The Values  The values can be of several possible types. They can even be other documents embedded into ours.
© 2008 Haim Michael Case Sensitivity  MongoDB is a type sensitive and a case sensitive database. Documents differ in any of those two aspects are considered as different documents. {“id“,123123} {“id“,”123123”} These two documents are considered different!
© 2008 Haim Michael Collection  Collection is a group of documents. We can analogue documents to rows and collections to tables.  The collection is schema free. We can hold within the same single collection any number of documents and each document can be of a different structure. {“id“:1423123} {“hoby“:“jogging“,“gender“:“man“,“telephone“:“0546655837“} {“country“:“canada“,“zip“:76733} Valid Collection That Includes Three Maps
© 2008 Haim Michael Separated Collections  Although we can place within the same collection documents with different structure, each and every one of them with different keys, different types of values and even different number of key value pairs, there are still very good reasons for creating separated collections.
© 2008 Haim Michael Separated Collections  The separation into separated collections assists with keeping the data organized, simpler to maintain and it speeds up our applications allowing us to index our collections more efficiently.
© 2008 Haim Michael Collections Names  Each collection is identified by its name. The name can include any UTF-8 character, with the following limits.  The collection name cannot include the '0' character (null).  The collection name cannot be an empty string (“”).  The collection name cannot start with “system”. It is a prefix reserved for system collections.
© 2008 Haim Michael Collections Names  The collection name cannot contain the '$' character. It is a reserved character system collections use.
© 2008 Haim Michael Sub Collections  We can organize our collections as sub collections by using name-spaced sub-collections. We use the '.' character for creating sub collections. forum.users forum.posts forum.administrators
© 2008 Haim Michael Databases  MongoDB groups collections into databases. Each MongoDB installation can host as many databases as we want.  Each database is separated and independent.  Each database has its own permissions setting and each database is stored in a separated file.  It is a common practice to set a separated database for each application.
© 2008 Haim Michael Databases  The database name cannot contain the following characters: ' ' (single character space), '.', '$', '/', '', '0'.  The database name should include lower case letters only.  The length of the database name is limited to a maximum of 64 characters.  The following are reserved names for databases that already exist and can be accessed directly: admin, local and config.
© 2008 Haim Michael Namespaces  When prepending a collection name with the name of its containing database we will get a fully qualified collection name, also known as a namespace. Let's assume we have the abelski database and it includes the posts collection. The abelski.posts is a namespace.  The length of each namespace is limited to 121 characters.
© 2008 Haim Michael Downloading MongoDB  You can download the latest version of MongoDB at www.mongodb.com.
© 2008 Haim Michael Starting MongoDB  Within the bin folder you should expect to find various utilities for working with MongoDB.  Before we start the MongoDB server we first need to create the folder where MongoDB will save the data. By default, MongoDB will store the data within c:datadb. We must create this folder in advance. MongoDB won't do that for us.  The mongod.exe utility starts the MongoDB server. The mongo.exe utility starts the MongoDB client shell.
© 2008 Haim Michael Starting MongoDB  The MongoDB assumes the folder where all data should be saved is c:datadb. You should create that folder in advance before you run the MongoDB server. We can create another folder and set it as the data folder instead of the default one.  Once the MongoDB server is up and running we can start the MongoDB shell command by executing the mongo.exe utility.
© 2008 Haim Michael Starting MongoDB
© Haim Michael What is Mongoose.js?  Mongoose.js is a JavaScript library that provides us with an object oriented interface for using the MongoDB in our node.js web applications. www.mongoosejs.com
© Haim Michael What is Mongoose.js?
© Haim Michael Mongoose.js Popularity  You can find a collection of projects that were developed using mongoose.js at http://mongoosejs.tumblr.com.
© Haim Michael Mongoose.js Popularity
© Haim Michael Installing Mongoose  In order to install mongoose you first need to have node.js platform already installed.  Using the npm utility you can easily get the mongoose module available on your desktop.
© Haim Michael Installing Mongoose
© Haim Michael Connecting MongoDB  Calling the connect method on the mongoose object we will get a connection with an up and running mongodb server. mongoose.connect('mongodb://localhost/test');  Referring the connection property in the mongoose object we will get the connection object itself. var db = mongoose.connection;
© Haim Michael Handling Connection Events  Calling the on method on the connection object we can handle its various related events.  The first argument should be the event name. The second argument should be the function we want to be invoked when the event takes place.  Passing over error as the first argument we can handle connection errors. db.on('error', function() {console.log("error")});
© Haim Michael Handling Connection Events  We shall write our code within the function we pass over to be invoked when the open event takes place. db.once('open', function () { ... });
© Haim Michael Code Sample var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/test'); var db = mongoose.connection; db.on('error', function() {console.log("error")}); db.once('open', function () { console.log("connected!"); var productSchema = mongoose.Schema( {id:Number, name: String}); productSchema.methods.printDetails = function() { var str = "id=" + this.id + " name="+this.name; console.log(str); }; var Product = mongoose.model('products',productSchema);
© Haim Michael Code Sample var carpeta = new Product({id:123123,name:'carpetax'}); var tabola = new Product({id:432343,name:'Tabolala'}); carpeta.save(function(error,prod) { if(error) { console.log(error); } else { console.log("carpeta was saved to mongodb"); carpeta.printDetails(); } });
© Haim Michael Code Sample tabola.save(function(error,prod) { if(error) { console.log(error); } else { console.log("tabola was saved to mongodb"); tabola.printDetails(); } }); Product.find(function(error,products) { if(error) { console.log(error); } else { console.log(products); } }); });
© Haim Michael Code Sample
© 2009 Haim Michael All Rights Reserved 72 Questions & Answers Thanks for Your Time! Haim Michael haim.michael@lifemichael.com +972+3+3726013 ext:700 lifemichael

Node JS Crash Course

  • 1.
    Node.js Crash Course HaimMichael October 4th , 2018 All logos, trade marks and brand names used in this presentation belong to the respective owners. lifemichael Part 1: https://youtu.be/fnwdm4yob2o Part 2: https://youtu.be/OWCDm5_RbRQ
  • 2.
    © 1996-2018 AllRights Reserved. Haim Michael Introduction ● Snowboarding. Learning. Coding. Teaching. More than 18 years of Practical Experience. lifemichael
  • 3.
    © 1996-2018 AllRights Reserved. Haim Michael Introduction ● Professional Certifications Zend Certified Engineer in PHP Certified Java Professional Certified Java EE Web Component Developer OMG Certified UML Professional ● MBA (cum laude) from Tel-Aviv University Information Systems Management lifemichael
  • 4.
    © 2008 HaimMichael 20150805 Introduction
  • 5.
    10/04/18 © abelski5 What is Node.js?  The node.js platform allows us to execute code in JavaScript outside of the web browser, which allows us to use this platform for developing web applications excellent in their performance.  The node.js platform is based on JavaScript v8. We use the JavaScript language.
  • 6.
    10/04/18 © abelski6 Asynchronous Programming  Most of the functions in node.js are asynchronous ones. As a result of that everything is executed in the background (instead of blocking the thread).
  • 7.
    10/04/18 © abelski7 The Module Architecture  The node.js platform uses the module architecture. It simplifies the creation of complex applications.  Each module contains a set of related functions.  We use the require() function in order to include a module we want to use.
  • 8.
    10/04/18 © abelski8 We Do Everything  The node.js platform is the environment. It doesn't include any default HTTP server.
  • 9.
    10/04/18 © abelski9 Installing Node  Installing node.js on your desktop is very simple. You just need to download the installation file and execute it. www.nodejs.org
  • 10.
    10/04/18 © abelski10 Installing Node
  • 11.
    10/04/18 © abelski11 The node.js CLI  Once node.js is installed on your desktop you can easy start using its CLI. Just open the terminal and type node for getting the CLI.
  • 12.
    10/04/18 © abelski12 The node.js CLI
  • 13.
    10/04/18 © abelski13 Executing JavaScript Files  Using node.js CLI we can execute files that include code in JavaScript. We just need to type node following with the name of the file.
  • 14.
    10/04/18 © abelski14 Executing JavaScript Files
  • 15.
    10/04/18 © abelski15 Node Package Manager  The Node Package Manager, AKA as NPM, allows us to manage the packages installed on our computer.  NPM provides us with an online public registry service that contains all the packages programmers publish using the NPM.  The NPM provides us with a tool we can use for downloading, installing the managing those packages.
  • 16.
    10/04/18 © abelski16 Node Package Manager  As of Node.js 6 the NPM is installed as part of the node.js installation.  The centralized repository of public modules that NPM maintains is available for browsing at http://npmjs.org.
  • 17.
    10/04/18 © abelski17 Node Package Manager
  • 18.
    10/04/18 © abelski18 The npm Utility  There are two modes for using the node.js package manager, also known as npm.  The local mode is the default one. In order to be in the global mode we should add the -g flag when using the npm command.
  • 19.
    10/04/18 © abelski19 The npm Utility  Using npm in the local mode means that we get a copy of the module on our desktop saved in a subfolder within our current folder.  Using npm in the global mode the module file will be saved together with all other modules that were fetched globally inside /usr/local/lib/node_modules/.
  • 20.
    10/04/18 © abelski20 The npm Utility  Let's assume we want to use the facebook module from the npm repository. Typing npm install facebook will download and install the facebook module into our platform so from now on we will be able to use it.
  • 21.
    10/04/18 © abelski21 The npm Utility
  • 22.
    10/04/18 © abelski22 Running HTTP Server on Our Desktop  We can easily set up on our desktop an up and running HTTP server that runs a web application developed in node.js.  We just need to write our code in a separated JavaScript file and execute it.
  • 23.
    10/04/18 © abelski23 Running HTTP Server on Our Desktop var http = require('http'); var server = http.createServer(function (req, res) { res.writeHead(200, {'Content-Type':'text/plain'}); res.end('Hello World!n'); }); server.listen(1400,'127.0.0.1');
  • 24.
    10/04/18 © abelski24 Running HTTP Server on Our Desktop
  • 25.
    © 2008 HaimMichael 20150805 Query String
  • 26.
    10/04/18 © abelski26 Accessing The Query String  The url module allows us to access the query string. Calling the parse method on the url module passing over req.url as the first argument and true as the second one will get us an object that its properties are the parameters the query string includes. The keys are the parameters names. The values are their values.
  • 27.
    10/04/18 © abelski27 Accessing The Query String var http = require('http'); var url = require('url') ; http.createServer(function (req, res) { //var area = req.query.width * req.query.height; res.writeHead(200, {'Content-Type': 'text/plain'}); var queryObject = url.parse(req.url,true).query; res.end('area is '+(queryObject.width*queryObject.height)); }).listen(1400, function(){console.log("listening in port 1400");});
  • 28.
    © 2008 HaimMichael 20150805 Event Loop
  • 29.
    10/04/18 © abelski29 The Loop  When Node.js starts, it first initializes the event loop and then it starts with processing the input script.
  • 30.
    10/04/18 © abelski30 The Loop  timers This phase executes callbacks scheduled by setTimeout() and setInterval().  pending callbacks This phase executes I/O callbacks deferred to the next loop iteration.  idle, prepare This phase is been used internally only.
  • 31.
    10/04/18 © abelski31 The Loop  poll This phase retrieves new I/O events; execute I/O related callbacks (almost all with the exception of close callbacks, the ones scheduled by timers, and setImmediate()); node will block here when appropriate.  check This phase includes the invocation of setImmediate() callbacks
  • 32.
    10/04/18 © abelski32 The Loop  close This phase is responsible for the invocation of close callbacks (e.g. socket.on('close', …);).
  • 33.
    © 2008 HaimMichael 20150805 MongoDB
  • 34.
    © 2008 HaimMichael What is MongoDB?  MongoDB is a flexible and a scalable document oriented database that supports most of the useful features relational databases have.
  • 35.
    © 2008 HaimMichael Document Oriented Database  The document concept is more flexible comparing with the row concept we all know from relational databases. The document model allows us to represent hierarchical relationships with a single record.
  • 36.
    © 2008 HaimMichael Flexibility  Using MongoDB we don't need to set a schema. The document's keys don't need to be predefined or fixed. This feature allows us an easy migration of our application into other platforms.
  • 37.
    © 2008 HaimMichael Scaling  When the amount of data grows there is a need in scaling up (getting a stronger hardware) our data store or scaling out (partition the data across more computers). MongoDB document oriented data model allows us to automatically split up the data across multiple servers. MongoDB handles most of this process automatically.
  • 38.
    © 2008 HaimMichael Stored JavaScript  MongoDB allows us to use JavaScript functions as stored procedures.
  • 39.
    © 2008 HaimMichael Speed  MongoDB uses a binary wire protocol as its primary mode of interaction with the server, while other databases usually use heavy protocols such as HTTP/REST.  In order to achieve high performance many of the well known features from relational databases were taken away.
  • 40.
    © 2008 HaimMichael Simple Administration  In order to keep the MongoDB easy and simple to use its administration was simplified and is much simpler comparing with other databases.  When the master server goes down MongoDB automatically failover to a backup slave and promote the slave to be the master.
  • 41.
    © 2008 HaimMichael Documents  Document is a set of keys with associated values, such as a map.  In JavaScript a document is represented as an object. {“lecture“:“Haim Michael“, “topic“:“Scala Course“, “id“: 2345335321}  The values a document holds can be of different types. They can even be other documents. key value key value key value
  • 42.
    © 2008 HaimMichael The Keys  We cannot contain duplicate keys within the same document.  The keys are strings. These strings can include any UTF-8 character.  The '0' character cannot be part of a key. This character is in use for separating keys from their values.  The '.' and the '$' characters have a special meaning (explained later).
  • 43.
    © 2008 HaimMichael The Keys  Keys that start with '_' are considered reserved keys. We should avoid creating keys that start with this character.
  • 44.
    © 2008 HaimMichael The Values  The values can be of several possible types. They can even be other documents embedded into ours.
  • 45.
    © 2008 HaimMichael Case Sensitivity  MongoDB is a type sensitive and a case sensitive database. Documents differ in any of those two aspects are considered as different documents. {“id“,123123} {“id“,”123123”} These two documents are considered different!
  • 46.
    © 2008 HaimMichael Collection  Collection is a group of documents. We can analogue documents to rows and collections to tables.  The collection is schema free. We can hold within the same single collection any number of documents and each document can be of a different structure. {“id“:1423123} {“hoby“:“jogging“,“gender“:“man“,“telephone“:“0546655837“} {“country“:“canada“,“zip“:76733} Valid Collection That Includes Three Maps
  • 47.
    © 2008 HaimMichael Separated Collections  Although we can place within the same collection documents with different structure, each and every one of them with different keys, different types of values and even different number of key value pairs, there are still very good reasons for creating separated collections.
  • 48.
    © 2008 HaimMichael Separated Collections  The separation into separated collections assists with keeping the data organized, simpler to maintain and it speeds up our applications allowing us to index our collections more efficiently.
  • 49.
    © 2008 HaimMichael Collections Names  Each collection is identified by its name. The name can include any UTF-8 character, with the following limits.  The collection name cannot include the '0' character (null).  The collection name cannot be an empty string (“”).  The collection name cannot start with “system”. It is a prefix reserved for system collections.
  • 50.
    © 2008 HaimMichael Collections Names  The collection name cannot contain the '$' character. It is a reserved character system collections use.
  • 51.
    © 2008 HaimMichael Sub Collections  We can organize our collections as sub collections by using name-spaced sub-collections. We use the '.' character for creating sub collections. forum.users forum.posts forum.administrators
  • 52.
    © 2008 HaimMichael Databases  MongoDB groups collections into databases. Each MongoDB installation can host as many databases as we want.  Each database is separated and independent.  Each database has its own permissions setting and each database is stored in a separated file.  It is a common practice to set a separated database for each application.
  • 53.
    © 2008 HaimMichael Databases  The database name cannot contain the following characters: ' ' (single character space), '.', '$', '/', '', '0'.  The database name should include lower case letters only.  The length of the database name is limited to a maximum of 64 characters.  The following are reserved names for databases that already exist and can be accessed directly: admin, local and config.
  • 54.
    © 2008 HaimMichael Namespaces  When prepending a collection name with the name of its containing database we will get a fully qualified collection name, also known as a namespace. Let's assume we have the abelski database and it includes the posts collection. The abelski.posts is a namespace.  The length of each namespace is limited to 121 characters.
  • 55.
    © 2008 HaimMichael Downloading MongoDB  You can download the latest version of MongoDB at www.mongodb.com.
  • 56.
    © 2008 HaimMichael Starting MongoDB  Within the bin folder you should expect to find various utilities for working with MongoDB.  Before we start the MongoDB server we first need to create the folder where MongoDB will save the data. By default, MongoDB will store the data within c:datadb. We must create this folder in advance. MongoDB won't do that for us.  The mongod.exe utility starts the MongoDB server. The mongo.exe utility starts the MongoDB client shell.
  • 57.
    © 2008 HaimMichael Starting MongoDB  The MongoDB assumes the folder where all data should be saved is c:datadb. You should create that folder in advance before you run the MongoDB server. We can create another folder and set it as the data folder instead of the default one.  Once the MongoDB server is up and running we can start the MongoDB shell command by executing the mongo.exe utility.
  • 58.
    © 2008 HaimMichael Starting MongoDB
  • 59.
    © Haim Michael Whatis Mongoose.js?  Mongoose.js is a JavaScript library that provides us with an object oriented interface for using the MongoDB in our node.js web applications. www.mongoosejs.com
  • 60.
    © Haim Michael Whatis Mongoose.js?
  • 61.
    © Haim Michael Mongoose.jsPopularity  You can find a collection of projects that were developed using mongoose.js at http://mongoosejs.tumblr.com.
  • 62.
  • 63.
    © Haim Michael InstallingMongoose  In order to install mongoose you first need to have node.js platform already installed.  Using the npm utility you can easily get the mongoose module available on your desktop.
  • 64.
  • 65.
    © Haim Michael ConnectingMongoDB  Calling the connect method on the mongoose object we will get a connection with an up and running mongodb server. mongoose.connect('mongodb://localhost/test');  Referring the connection property in the mongoose object we will get the connection object itself. var db = mongoose.connection;
  • 66.
    © Haim Michael HandlingConnection Events  Calling the on method on the connection object we can handle its various related events.  The first argument should be the event name. The second argument should be the function we want to be invoked when the event takes place.  Passing over error as the first argument we can handle connection errors. db.on('error', function() {console.log("error")});
  • 67.
    © Haim Michael HandlingConnection Events  We shall write our code within the function we pass over to be invoked when the open event takes place. db.once('open', function () { ... });
  • 68.
    © Haim Michael CodeSample var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/test'); var db = mongoose.connection; db.on('error', function() {console.log("error")}); db.once('open', function () { console.log("connected!"); var productSchema = mongoose.Schema( {id:Number, name: String}); productSchema.methods.printDetails = function() { var str = "id=" + this.id + " name="+this.name; console.log(str); }; var Product = mongoose.model('products',productSchema);
  • 69.
    © Haim Michael CodeSample var carpeta = new Product({id:123123,name:'carpetax'}); var tabola = new Product({id:432343,name:'Tabolala'}); carpeta.save(function(error,prod) { if(error) { console.log(error); } else { console.log("carpeta was saved to mongodb"); carpeta.printDetails(); } });
  • 70.
    © Haim Michael CodeSample tabola.save(function(error,prod) { if(error) { console.log(error); } else { console.log("tabola was saved to mongodb"); tabola.printDetails(); } }); Product.find(function(error,products) { if(error) { console.log(error); } else { console.log(products); } }); });
  • 71.
  • 72.
    © 2009 HaimMichael All Rights Reserved 72 Questions & Answers Thanks for Your Time! Haim Michael haim.michael@lifemichael.com +972+3+3726013 ext:700 lifemichael