NodeJS API Development with Express MongoDB and Mongoose | Ajay Srinivasa | Skillshare

NodeJS API Development with Express MongoDB and Mongoose

Ajay Srinivasa

NodeJS API Development with Express MongoDB and Mongoose

Ajay Srinivasa

Play Speed
  • 0.5x
  • 1x (Normal)
  • 1.25x
  • 1.5x
  • 2x
32 Lessons (3h 8m)
    • 1. Course Introduction

    • 2. What is Node

    • 3. Installing Node

    • 4. Installing Visual Studio Code

    • 5. Blocking vs NonBlocking

    • 6. Hello Node

    • 7. Core Nodejs Modules Section Introduction

    • 8. File System fs module

    • 9. HTTP Module

    • 10. Global Modules

    • 11. NPM Modules Introduction

    • 12. NPM Yargs

    • 13. First Project

    • 14. Express Section Introduction

    • 15. Hello Express

    • 16. Express Serving Static HTML

    • 17. Express Routing

    • 18. Express Middleware

    • 19. MongoDB Section Intro

    • 20. MongoDB RoboMongo SetUp

    • 21. MongoDB Using Native NodeJS Driver

    • 22. MongoDB CRUD Operations

    • 23. Diary App using Nodejs MongoDB

    • 24. ES6 Promises

    • 25. ES6 Promises with MongoDB

    • 26. Mongoose Intro

    • 27. Mongoose Note App

    • 28. Build API Customer Info

    • 29. API Authentication Password Hashing

    • 30. API Authentication JWT

    • 31. Adding Customer API to GitHub

    • 32. API Deployment to Heroku

  • --
  • Beginner level
  • Intermediate level
  • Advanced level
  • All levels
  • Beg/Int level
  • Int/Adv level

Community Generated

The level is determined by a majority opinion of students who have reviewed this class. The teacher's recommendation is shown until at least 5 student responses are collected.





About This Class

NodeJS is by far one of the most popular web server technologies.

NodeJS is used by pretty much every big company that needs speed, agility and
concurrency at its core and NodeJS developers are always in demand.

In this course you would learn NodeJS from scratch, Express framework, MongoDB database and Mongoose and develop API s using them.

I have designed the curriculum to get you started with practical coding examples right from the beginning. So whether you want to start of your career with web-technologies or make a career switch, this course is just right for you.

You would first get a brief theory on each of the topics and then dive straight to code-along lectures. 

You would first learn:

  • Basics of NodeJS, how it works under the hood and what makes it so great
  • Core NodeJS modules by way of practical coding examples
  • Node Package Manager(NPM) and how you can import existing modules/libraries and use them to build your App or API
  • Node's Express framework and build a web-server using it. You would get introduced to the concept of developing an API
  • MongoDB and learn to interact with the database using NodeJS native drivers
  • Mongoose - a very popular ODM used alongside MongoDB
  • Then you would build a professional looking API using all your learnings and test it.
  • You learn about Git to put your NodeJS  API code under version control
  • Finally you deploy your API built using NodeJS to a cloud platform - Heroku

At appropriate stages you would be given exercises and projects to work on that would help you explore on your own and also refresh your learning.

It would greatly help if you have a beginner's knowledge on coding in Javascript

The course goes over the topics step by step in sufficient detail and adopts a code/work along method so that students can run the apps or API s in parallel to the instructor.

The theory has been kept to a minimum and crisp, just enough to get you the context before you start hands on. 

Meet Your Teacher

Class Ratings

Expectations Met?
  • Exceeded!
  • Yes
  • Somewhat
  • Not really
Reviews Archive

In October 2018, we updated our review system to improve the way we collect feedback. Below are the reviews written before that update.

Your creative journey starts here.

  • Unlimited access to every class
  • Supportive online creative community
  • Learn offline with Skillshare’s app

Why Join Skillshare?

Take award-winning Skillshare Original Classes

Each class has short lessons, hands-on projects

Your membership supports Skillshare teachers

Learn From Anywhere

Take classes on the go with the Skillshare app. Stream or download to watch on the plane, the subway, or wherever you learn best.



1. Course Introduction: Hello and welcome to the course. Will AP ICE using No Jay's Express, Mongo, DB and Mongrels. Norges is suicide. Jealous Script Engine Express. A no nonsense Web framework for no Jays mongo DB is a great document based database, and mongrels is an easy to use sodium for mongo. Db. With this course, you will learn all these technologies and toes and equip yourself to write a fully functional rest FBI using them. I'm magician Yuasa, your instructor for the scores, and I'm glad that have chosen to advance your career with the scores. That aims to help you learn one of the most popular and lucrative technologies off current times. Just for a quick history on Norges. It was created by Ryan Doll in 2009. It later went through a few changes, one of them being that it was named. I own orgs for a while, and finally it got its old name back with Notre Lease For and readings that name to date, No do is use pretty much by every big company that needs speed, agility and concurrency at its core, some of them being Netflix, PayPal, Walmart, IBM, Lincoln and many more. Its usage is ever increasing and always in demand. I have designed the scores keeping this demand in mine so that you learn no express. Munger, DB and Long was quickly also accompanied by exercises and assignments that will help you apply what you learn throughout the course. It has been designed to start you off with practical according examples. Right from the beginning, you would first military on each of the topics and then dive straight to court along lectures. Here's a quick course overview. You would first learn what is known, and wire does the preferred choice of technology with basic installation for no done. You then understand, with some examples, what makes it so popular today. Next, we will explore the concept off a North Morgan and how you can use it. You will learn some very important court nor Jace models by way off practical courting examples. And then he would learn what is not package manager shortly called NPM and how you can import existing modules or libraries and use them to build your app. You would then proceed to learn one of the most popular framework we express, and will the Observer using it then you would learn about Mongo DB and learn to interact with the database using no GST native drivers. You will also learn mongrels, which is a very popular odium used alongside Mongo DB. Finally, you would build a need. FBI using all your learnings in the course and district, you learn about get to put your corn and awash in control. And at the end of the course, you take your FBI to production by deploying it to her local at appropriate stages of the course. We would also be given exercises and projects to work on that would help you explore on your own and also refresh your learning now during the course at any time. If you have questions, please feel free to post it in the Q and a section for the lecture on. I'll do my best to help you resulted again. It's great that you've chosen to advance her career further with the schools on. I hope you make the most of it. Thank you and see you in sight 2. What is Node: in this lecture, you will understand what is No Jace, what it is comprised off and what makes it stand apart from a lot, many other technologies out there. If you open the homepage off, no GS start arc. The first thing that is presented to you is the definition off Norges that reads. No Jesus, the Java script. Runtime building, Crooms v a JavaScript engine. No Jay's uses and even driven non blocking I your body that makes it light weight. An efficient no Jesus package ecosystem. NPM is the largest equal system off open source libraries in the world, so the first thing is that it is not a programming language. Instead, it is a runtime for running JavaScript core. And this runtime is based on Google Cruz V eight engine. No, what does this V eight engine? Every brother has an engine that can run the underlying JavaScript code. One of the more efficient ones is Google Chrome's open source, high performance V eight engine that is actually written in C plus plus. So when no Js was founded, this high performance rear brother engine was taken, and with the addition off a few libraries, it was implemented as a server or as a standalone process. This meant that in addition to just running Java, script notes could interact with the fine system with the network and other hardware and all using plain old JavaScript. It is important to note here that you need not know what learn c++ to write nor deer school . The next thing that the definition says is that it is even driven in which certain kinds of objects called emitters periodically Emmett named evens that cause function objects to be called the simplest form. Often even that can be emergent is opening off a fire as soon as the finest opened. It triggers a named even that can be bricked and process likewise, that are even that get triggered for every Io operation on Nor and until that, even two Stryker note keeps processing, other requests or other lines. Of course, the last thing is that it uses a non blocking you mourn. I o refers to any operations that the program has to perform on the hardware. Traditionally, whenever an Iot operation takes place, the rest of the program is kept on hold. Until that I owe operation is complete. This is called blocking. Blocking occurs when the execution off one set off JavaScript code phrases the execution of further lines of court until it completes. In no days on the Iot. Methods in the standard library have asynchronous versions that enabled writing non blocking cold. This results in functionality where the North engine is working on io and that does not freeze the execution of the rest of the court. It can't and a desk keep working on the rest of the JavaScript court. When are you is being taken? Care off? It runs single treated, non blocking core that is both memory on time, efficient. I haven't wanted exactly how this works. In a later lecture once we installed Norges No, what makes known so popular earlier in plain old JavaScript, you could write code restricted to the brother environment. But with no, you can do much more similar to other programming languages like Java brighten our BHP. You can manipulate fine systems, interact with system level sockets and of course, you know, much more efficient obey. And you could do all of this using seems in taxes. JavaScript adopt this. There is a note equal system that consists off thousands off useful libraries that can be used using the north Package Manager One of these features makes nor what it is today. That being said, we will see all this in action right in court yourself throughout this course that brings us to the end of this lecture. Hope you enjoyed this. Thank you. 3. Installing Node: in this lecture who would be installing no jails for your operating system? Open your brother and go toe no jr's dot org I have a windows always. So I'm gonna download the latest wash in at the time of this recording. The latest version is eight. Got mind or tree? Click on it and save the file one's domino order. Open it. Accept the license agreement and select where you want to install, nor Js in the next prompt. Just take a note off God, competence are getting in Start. You have the nerdiest runtime, the North Package manager linked to online documentation on finally something that adds nor to the system path variable, click next and install. I'm gonna fast forward the installation in the interest of time. Once the installation is complete, open a command window and type. No happen re. That should list the washing off nor Jay's. That was in start. In my case, it is a don't mind or three. If you have done really later washing, it should show that that takes us to the end of this lecture. In the next lecture, you would be installing visual studio code where he would be pretty much writing all of the Nordea score during the course. Thank you 4. Installing Visual Studio Code: In this lecture, you will install visual studio code for developing no applications. I use visuals for your court for no debugging usually, and I strongly recommended for beginners to note, you are free to use other tools, which are mostly feature film text editors, like atom off brackets. Sublime. But I prefer were school. It has a tunnel features some of the most popular ones being intelligence that helps you explore module contents and also called faster, especially for a beginner. It also has an integrated terminal source control, integration, streamline, debugging and many more. You will see many of these features in action during the course and then probably appreciated better. First, let's don't will be a school and install it. Goto https for what's fresh, cool Dark visions tell you dot com. Download the software for your operating system. The installer is pretty basic. Just click a few next, and you should be good to go. Once the installation is complete, launch via school. Once it is open, you see an option to set a workspace folder. It will be doing all of a book on North. Who's your Let's set it up? Click on the link I'm gonna set it up on the desktop by creating a new folder called Nor Gs . Once done, the funder appears on the left pain. And you can create your finds of folders inside off it. We'll be bringing on via scored and on this workspace thrown scores. In the next lecture, you would be writing your first no jail school. Thank you. 5. Blocking vs NonBlocking: in the introduction to know J. S. You heard about blocking and non blocking aspect off Norges. Now that we have known and our development I d installed, let me give you a dime off what it really means. No, not really. If you're unclear of certain aspects of the court here, you've not exploded yet. In the course, the focus here is mainly for you to understand the non blocking aspect off Norges. Here I have two files blocking the jays and non blocking Georges. Both have quarter turn to read a file and output the times before and after reading the fight. The first blocking No dears file has a function. It is read file. Think that reads the file and it blocks no James from executing anything else during this time. Let me open the terminal and run nor blocking Gorgeous. No, look at the non blocking RGs file that reads the same fight. However, it does not block north from looking at the rest of the court during the Iot operation. I'm gonna run nor non blocking Georges in the same terminated. Now observe that the non blocking Js file worked on the court written after i o. And once the Iot work was complete, it printed finished reading. Do not misunderstand here that the non blocking court took less time to read the fight. Notice that the time taken to read the files are pretty much similar with both blocking and the non blocking coat. However, the efficiency off node lice in not getting blocked by Oh, and moving on with the rest of the court, this will give you a good peek into the non blocking concepts off Norges. As you work your way through the course, this is gonna get a lot more clearer. Let's more into the rest of the courts. Hope you enjoy this. Thank you. 6. Hello Node: in this lecture would be writing you first nor J school. As is the tradition. Well, first into print a hello world kind of message before beginning on any new technology or a programming language. That's just to ensure that the runtime is working as expected and no links are broken. Let's do that. I'm gonna create a folder in the workspace and call it Hello? No. On the day and were cleared. If I in court hello dot jizz I just have one line in it. Concern dot Now here's an interesting thing. It's called intelligence that I spoke about earlier when you were installing via school intelligence lists all the methods and variables available in a certain body. Here, you see a big list when you typed dot part of that list we just picked lock and see. Hello. Please. No. Now, in order to run this, you can either open the commander pumped or the other option is there via school. Provides an integrated terminal under the view menu item. I would be using this extensively throughout the course in the terminal. Change to the territory. Hello, Nora. And think no space. Hello, gorgeous. This should bring Hello, Nord. Congratulations. You've written your first nor G is good and it is working as expected. That takes us to the end of this lecture. Thank you. 7. Core Nodejs Modules Section Introduction: in the section will expose some court nor Js warnings. Well, it was a very useful and frequently was once that you get a good hand off working with them . Obviously, all the corn mornings cannot be covered here. So in case you want any specific morning that's not covered and for your work, please leave a message and I'll try to address it, then even started. No Js in Kim Created started the course it off models Ahmad Younis, similar to a luxury that there was a functionality, even used these core values reciting the empirically where you can start. No Jace in the previous literally, when you saw the blocking with his non blocking example, you actually saw one of the non JIA's memorials in action in order to see the full Mr Cool borders on your process. One of the genes speech. It glows, and you call a question that you start that opens up the documentation to all the available FBI's, but that worship. But each of these models walking toe the official documentation is that's for you. To get a feel of is a literal when you want to write something on your own. Then you know where to look and how to understand what you look at. This can be daunting in the beginning, I understand. But we kept credited with practice here on the left, you see a wholeness or features. Some of them are one human sense are just constants. I'm just more one simple, more junior. Now it is used more often than any other modules is the console module, as you see here consists off console class, but it's like law error, and one these with this can be caught from anywhere in court to print to the awkward stream . This was just an example. In the coming just you seem more court, more Jews and also book on each one of them. So see you that 8. File System fs module: In this lecture, we will explore the FS morning. The efforts model is used to interact with a file system. This morning has functions in both the Congress and the synchro spots. Let's explore it. Are the four mornings Fourtou creating a new file card file? DOrtiz. The first lane is too important for the first morning flight. Const Fs is he going to require efforts? This is just like what we did with the http Mahdi. The F S model can be used to read write the need happen into lots more fights. Let's try the lead. Fine weather first. If you look at the documentation for refight, you see that the first parameter is the fine. The second option Parliament being options like the in according to be given and the last is a callback function that gets called once the finest straight first create. If I could read dot txt and add some context would Syrian and in your core right if it's door refi and give the first batter murder as reid dot txt in goods we don't want to give any in according options. So let's just right the Colbert function that passed the editor is the first parameter and the data as a second perimeter in case of an edit through to the offer. So right if and then just told you. And then the follicle spell right the data to the local street by writing concerned on club data dot to string. Now say the fight opened the dominant and I know filed or days and see the open due to the country's off The read guardians defy Next up will explore the A pen file method. This mother happens to an existing file. The file doesn't exist. It created We do it by writing f s a fair fight with you when you find him. Could read one door Txt So in our case, this fight doesn't exist So it's gonna get creative And then do you think it'll be appointed as a pendant data and the compact function which digs in resin argument. So it's going through another. If there is an editor, I thought it was very just loves completed burning seem to fight and again the dominant right Nor find out years notice that read filed this rectified and a pedophile has created a new file call Read Wonder txt good also just happen someday. Do the existing fight as well. Next up, we'll explore Harper. Did you friends? In order to defeat fights, you can use the handling within similar to the upper and find material. The callback function. Your state's one other argument. Now we want to believe the real wonder Txt file i f s star Hundley need wonder txt on the callback function x the other argument. And once the relations complete, it's gonna just love completely believing that's it. Saved the fight at light again Already no foundered jays. In this case, you're running really firing a pen file on the link mattered all three of them from the same old application. No, it is the order of execution believed completes first, then read and finally a pending or writing to new file. This also reaffirms and mom blocking aspect off. Nordea's really happen. Take longer times or no just moves on to the next function in sequence and then completes that. And then once it is ready with the other functions, it finishes them. That takes us to the end of this lecture. Hope you enjoyed it. Thank you 9. HTTP Module: in this lecture You explore the http Martin, you can create your own extruded. The server is in this morning the basic rules for using a model in your court. Is that you, Nitto? Important? Using the required keyword. Let's get started. But when your workspace in via score create a foreigner in your workspace and call it score one use under that. Create a new fine corn estupido RGs for exploding the extra every morning. I said earlier. The first line is in order to important what you're using required keeper. You are true that create a constant cost yesterday be Is equipment required as to keep line entered the cynical, but that is not absolutely necessary. It just makes for better core practice. The next step is to create the server. If you look what it's really be. Models, doctor, magician. You see that Osama take your record creates out at the very end of the morning local tradition. It takes a request listener function that in term consists off a request and response as perimeters getting from in there. Right? Const cellar is equipped. Extra baby daughter creates away, and as we saw the documentation, it digs a function is an argument that in turn, has request and response as parameters. So we cleared the function with request and response, and we're here, and I'm using the Arab function, which is a new year. Six weeks off. Writing and animus functions. The implementation off the anonymous function takes in the question response objects on it . Rays are 21 http. Status score to the header. We do that by writing response dot Right here. 200 on and conveyed anything that he wants. You right, settler. Clear Did and then sends a response message. Okay, you say rest our end off. Okay. Now the silver needs support that it needs losing to. So we like, so not listen. Board 3000. You could stop. You are You can also write a function that prince a console log statement that says OK, it's listening with 4 3000 That's just so you know, that terrible starter once done either opened the command prompt. Navigate to the folder where you created the marking are open the integrator terminal B, A score which is a lot more easier and time nor yesterday. You, Georges. As soon as you start the more. Did you see that This over is listening on a port 3000. Let's validated. We'll put up and I local host calling 3000. You get a response booking, not our chicken Extra TB head of Got the Status 200 with the status message. Right? Click on the browser and click on Inspect. Go to the network there and then disregard the bridge. How does the intricate the status message? That's awesome. So you just created You don't actually be server that can be accessed from Rosa. That's a pretty good start In the coming lectures will explore more such core borders in action. Hope you enjoyed this. Thank you. 10. Global Modules: so far you have made use of modules which you first imported using require. There is one thing worth noting here why you don't have to require the STB module in order to use it. You did not have to do that in order to use the console body because because that model is a global model who find out the list off all global models. Open known indeterminant and I Global. You see various more use that are available to cement its like console process before on a few more typing each one of them. This Smith It's in that model and these with its can be used directly in any no Js fine. We don't really have to specifically require them. Initially, there are keywords like underscore. Underscore the name and underscoring the school filing that are not really global models. But these will be off very good use you. It doesn't use these in our cool. Create a new folder in your workspace and call it global Body was and then create a 500 call it global dot Js. Now let's clear the function to print something to the concert, we make use off the underscoring the school Find name and the underscore on school. Dear yard name the right function Putting something I console Don't look I am global And then I console Lord Law. I am here and give them that is true name Finally mass on a school in the score file name Next on the set. Time would function That in turn caused print something method After one second I said I'm on. Bring something coma 1000 seaward and run the ab. See the underscore Underscore Delia name Prince The current directory on the underscore The school finally Prince, stay absolute part off. The finally would be using this in a later exercise. 11. NPM Modules Introduction: in the previous sections, you learned about what is no Jay's on, although some of its core more deals more often than not, it would require the use third party modules to achieve some functionality. And these are not in start along with no. These more news consists of packages off reusable notice scored that solve some of the most common problems and available to be freely downloaded and used. You don't have to do it manually as there's a component called No, the package manager that does under this for you. In view as it is, chocolate called, is a package manager for no is the world's largest package industry, and it can be accessed. Oh, NPR. Jeez, Dark Ambien consists off the website itself at eight PM gears dot com with you discovered packages that you need to use, and it also consists of a command line utility or a command line interface, using which you can download an MP in package are also publish package toe MPM and comes bundled with North installation. You know, very fight that open a commander window and like envy, Um, I feel these. Come back the worship to the worship at the bottom off MPM documentation page. If it is lure, then you can a bigger with NPM install in view at the trade latest hyphen G. Where I fungi means global. Let's go ahead and write some. Gordon. Make use off some off the MP. More news that it's not more care. First, create a new directory and call it in PM Modules. Now the command window are the integrated terminal type, the command MPO in it and magenta. What this does is that it initialize is this particular territory for NPR. It asks a bunch of questions as to what you want to leave this more do and who is the author of this more dude and so on and so forth. Just accept all the before values and you didn't go. What you see is that it creates a final Accord package partisan as and when you install new models to this application, this Pakistan decent keeps getting updated. Let's first explore a simple third party morning record low Dutch Lord ashes used for a manipulation spring manipulation math functions on much more. For a full list of Lord Ashe methods, you can visit its documentation page at https Lord, I struggle as a first step before importing anymore. You check if the model is actually presented in PM's registry and see its popularity order in PMG is dot com and search for Blue Rash. If you look at the beach, you will see that it has been imported and used very widely, so we can tell that it's quite safe for us to use it in our applications. Next, go to become my problem and I in view install Lord Ashe. This government has a couple of things. First, it creates afford a corn nor underscore more news under your application. And next it imports the Lord Ashe from what you would under it. Second, it also updates the package store Jason filed with the dependency section point toe, the Lord dishwashing. That was important. No, not only use it in our core as learned earlier when you go first, require it as a popular way accusing Lord Ashe you can recorded using const underscore, is he quinto require low rash before using good. Let me quickly showing the documentation for Lord that lists is the tongue off utilities that can be used on the imbue Lord Ashe Page. Click on the link that picks in tow. Lord, I stopped. Come on, Documentation, Pete, You see on the utilities that it provides, let's try a dignity. So in an application I consumed or block on the school dark. Now, now I see the fight and the command window type. No, Lord Ashton, Jace, this prince at the current time, in milliseconds since Jan 1st 1970 let's try a simple stream function like a camera case. You can take console dot lock on the school dot camel case and giving and give any string that you want and we're going Hello World off. No, save it and run it. You see that they will put this camel cased and the output doesn't contain in these places . Apart from these there also, Anne, functions like index off or the with automated already used quite frequently to use them on you need to do is again involved. Those methods in your application I consumed outlawed on the school index are the input is in adding I'm gonna give a simple, very like 123 And let's whether you find the index off. Three. See everything going it. It's gonna give you the correct Don't book the index off. Three is, too. You could also modify and today, removing the mentor at another additional element to it, calling simple methods. Let's try the without method. So again, the input to the without method is ready. 123 And let's remove to from this. Okay, save it and doing it again, and you're gonna get the output without toe. So your opportunity consists of just the numbers with one, and they feel free to explore. A whole lot of other methods of Lord Ashe can be pretty useful just to get yourself accustomed to installing MPM packages. Initializing another. You can try one more on your own. It's called uppercase. Do you remember the hyphen? Its upper life in case there's one more without the hyphen and you don't need that for this exercise. Upper hyphen Case package converts any string that you give it in tow. Uppercase. Quite simple. Women with steps create a product instant shoot and PM and start the package on. Finally write your core was the video and give it a try. Okay. Hope you managed it. Yes, I would do it. I'm gonna use the same food Olympian more deals and create a new file called uppercase tortillas. Since we wanted the instant she did this for under two. B minus Brian B. M and McDonald's on and be a minute again and we run and view install upward. I've been case once done, look at the Pakistan adjacent file and know that it is updated in a little required the model Everything constant you see using quinto require about half in case I know not convert anything to upper case You just need to in walk the uppercase minute So right concerned outlaw uppercase off. No one is you see in brackets. Hello. Well, that it's a wouldn't run. You will see the upper case of hello one that princes to the end of this lecture The next lecture he would be working another popular Indian package called yards that is used to get Come on, my arguments. See you there 12. NPM Yargs: in this lecture, you're gonna learn about yarns. Yanks is a very powerful and a very popular NPM package that is used to get command line arguments. Meaning when you run the program, you can provided parameters right from the command line from where you would launch your app. It was understand, Britta with an example. If you remember in our core model section we hardcore did the file name to be read are offended or to be deluded. Now it is extent the filed RDS application begin to find name to read using yards. Create a new file call yards Georges no, from the command line installed the yards package using NPM install yards, double hyphens. Say now all you need to do to get started with reading command line arguments is declare a variable. Where are green is in Quibdo require off the yards in courts dot are green. Now, as for the documentation here on, get hub doing this will get all the arguments Where does this spring are? Degree and see what we get Type consoled on clock our agree save the fine and in your terminal type nor Yorks gorgeous command double hyphen A. Is equal to one double hyphen B is equal to two and double hyphen. See, he didn't. This will bring the common that we entered which was CMD in the underscore away. And the battle murders that we give as easy equaled one and visible to do are shown here on the perimeter. Double hyphens. See that we give. We didn't do a value doing so. It is taken by default as true on the dollar. Zero is the application name. So any flag without double hyphen is considered as a command and it comes under the underscore. Very and all the parameters without a value are considered bullion true by different now back to our application. Since we're doing some file handling, we required the core efforts more dude. So right const efforts is it Quinto required efforts in quotes. We plan to give to arguments for reading the fine one should be a read flag. You know how to read the fine on the 2nd 1 needs to read a final name that needs to be read so well right? If I agree dot underscored zero is equal to read and our agree not find him is not equal toe undefined. Then we'll run the read fight sometime. Fs dot reid file and read the fine name from the command line so we can write our gui dot file name and the callback is gonna take editor and the data as part of me does. And if there is an editor, then we're done concerned about log Better reading Fine Onda Bend If I limb if all goes well, type console door clock did, uh, dot to string At the moment we just stick to read some type is considered log Incorrect Good mind Save the fine and train running the up but the command nor Yorks Gorgeous give the Commander's read double hyphen file name is equal to read dot txt independent. You should get an editor that stays ever reading the fight because we've not place to find there yet. Let's go ahead and create a file in the territory and write something in it and run the application again and you see the file contents. If you miss passing any argument for example, if you just type Norges TRX Georges read, you would get in current command. Next, we look into deleting a file generally when you delete a file, the system double checks with you. If you have not accidentally pressed delete, we can do the same in orgies. That is, by using a model called the Read Line. It can dream standard input by the user we use read line and yards together to accomplish delicious First required the model by writing the line. Const read. Line music will do. Require read line in courts. Now ask for documentation. Read Line provides an interface for reading data from a readable, scream like process. Start Estili Iron. You can create an interface using read line dot create interface method. Let's do it in our application, we can write and CIF our greed don't under score of zero is equal to delete Andi. Our agree dot finally, um, is not equal toe on defined. Then we're gonna create the interferes using Const. Arnold is equal to read line dot orient interface, and the create interface method digs an object which has input as process dart, STD I in and output as process, nor a sturdy old next. Ask a question to the user are dot question. Are you sure you want to delete and upend the file name droid are greedy dot file name and a question mark, and the Goldberg takes answer. We'll have a flag to indicate if the delete completed or not type where the leader is equal to True. If something goes wrong, we'll changes to falls. Now, if the answer is yes, we'll delete it. Else will disclose the read line interface so DYP If answer is it will do a book. It's way. Our answer is equal to lower case way. If it's dog unlinked, our gov dot file name and the unlinked Britain, as we saw earlier, it takes a call back. That has better if editor concert Don't look, enter believing fine and a friend of filename to it our greed, our filing and then closed the interface with our Lord clothes and said the billeted flag to false. Now, if the leader is still true, then type console don't log completed deleting the fine and the Brenda fighting him. Do it our agree dark file name. Finally you close the ARL interface with our dark clothes, the final else If for checking the answer, if the answer is not, yes, then which is gonna close the interface with our lot close. Same Defy. Now run the fight by typing nor yards. Don't years delete double hyphen file. Name is equal. Do really dark pigsty. And then you get a question. If you don't want to delete the fight, I know our end on the interferes. Just closest. If you give away, then the fight against deleted. That brings us to the end of this lecture. In the next lecture, you will use all your learnings until this point in the course and implement them in writing your first simple project to see you there. 13. First Project: Here's the somebody off what you have learned so far you've learned what is No. It's basic installation and center. You didn't learn that their core Norges modules and also worked on a few of them. He wants to learn about the node package manager and how you can import reusable packages to your court and work with them. In this lecture, we will put all that learning to test when you create your first nor genius project for your project, you're gonna create a Web server using the http model. If this server is accessed using another browser, it needs to return a static HTML page that consists off some form data. If the farm gets somebody, then you write some data back to the brother. Why you do this? You also need to maintain a log off the server that logs. When the server was started, what methods were called like whether get was called or a post was called and also when it was called a static HTML Page is part of the resources for this lecture that is just to aid you in your project. You can use it if you like, was the radio and give it a go once. Done. Quickly. All right. Hope you were able to do that. If not, good try. Just so I Woodward on what off? Let's create a new folder Corn First project. Then I'm gonna run npm Any done it except for the different values. Now, finally, I'm going to copy the static HTML page it with a Web folder under the project. Okay, I'm gonna first create a longer Js Morgan that rights to the law. And now, since this right Stofile, it requires the FS model I'm gonna in Gordon, right? Const Memphis is equal to require efforts. I also plan to use the Lord Ashe and be a model for making use off the date function. Now also, you could make use off the date dark nominated without using the Lord ish NPM model. So on the terminal run NPM in strong your life Double hyphen Sam, once complete in the longer gs right, const underscore is equal. Do but inquired Lord Ashe Next ready function long That takes in the big auto return to the law. Someone rate where law is equal toe function. Log off data And when I called the happen filed matter off the efforts Morning. So if I start up and file the finally was gonna be longer txt and the data toe building is data and will upend the current time to it with the underscore dot No. And in case often better. I'm gonna just throw it out. Finally export the log available by using module dot Exports is in Quito Log. Next, I'm gonna create this Howard Orgs Morgan, this more doing is going to create the server and it's also going to read the starting HTML file. So we need the efforts and the extra deeply Models Road, const extra deeply is equal to require Minster Debry and constant efforts is equal to recoil fs We also plan to use the longer module to rate to the law. So far, you have used required on only no jails are gonna be immortals. You can also import your on models using the require right const log is equal to required dog Howard's life longer. Now let's was create a server using the http door creates over method as winter in the extra tp lecture right, http dot creates sever And as we saw the create servant but it takes a listener object that contains the request and the response objects again. Now, if the request mother is equal toe get, we're gonna log, Get me that car. And also for the woman Mitch is gonna respond back with are simple string Lee restaurant. Right? You're gonna get as if that inquest Dartmouth an is posed, then log post with the court. Also respond back. Weren't you called post and then ended? Finally. Listen on the board member 3000 that's it at the moment will not bring there any html form back to the browser. We just just the basic functionality just to make sure the log and the request responses functioning as expected. This is just rain showed everything is properly linked up. Now save your friends and started application from the dominant. Okay? No. Several Georgie's. As soon as you start the server, we should see a log entry that says listening onboard. 3000. Next open your frozen in goto entry. DP woman slash local host 3000. You should see a message back and also a log entry. Next, I'm gonna write the function that actually renders the HTML If I for that I'm gonna create a separate function called this platform So right function display form and it just takes in the response object on this is going to make use of the read file method off the fs morning. So if it's don't read Fi And if you remember from the Global Models lecture, we can make use of the underscore underscore d our name to refer to the current directory. So right underscoring to school for the name Andi Apprendi forward slash web was left index start HTM in Tokyo And finally the call back with better and the data If there is an editor , I'm gonna just throw the error 15 school been and great response dot but right Ted 200 Clinton type is in quinto text slash html Also right response dot Right did, uh, and ended This function can be called from anxiety if block for the get method. So coming to the line that says response don't right. You can get and replace that with display form and positive response. Object up next, save your friends and restrict itself. Now, if you go back to your brother and refresh the page, you will see a simple form for the submit button. Clicking women is gonna call the extra TP post within, and you see a response that says you call the Post, go back to the log and verify if everything is getting log. We should see everything right from when the several starter and when each mother was called And when this hour responded, That's it that completes your first project. Thank you. 14. Express Section Introduction: so far in the course you have learned about nor days, some off its core modules and also about a few NPM packages that you could import and write your own models with this foundation. I believe that you should be a little more comfortable with no and also programming and no Jay's compared to when you started in this section, you will look at a very popular framework called Express that is used to create the applications rapidly. Using node.js Express is so popular that many equal learning Notre with Learning Express Express is basically a Web application framework for Norges Pro is a powerful set of features to efficiently manage roads, requests views, along with a beautiful boilerplate boy of applications. As the express homepage express jeans dot com says it's a fast on opinionated, minimalist framework. Fast. Yes, it is both to develop and to run. You will know that as you get used to it, un opinionated and minimalist because it contains the basic framework to build a server. And all of the additional functionalities are differ toe plug ins, and it does not prescribe the best way to write your application. So you're free to take the framework and implemented your way. It's also free and open source. And just like any other MP of module, you could just install it using NPM and also start using it. Okay, that's about the basic introduction to express. Let's get started with it right away. 15. Hello Express: in this lecture, you're gonna create your first hello express application. In order to use express, you need to first install it. Using envy, you create a directory called Hello Express in your workspace on the dominant initialized the territory i n b m in it and accept all the defaults. Next type in B m install express double hyphen. Say this installs express and saves it in the package or Jason fight. Now create a file called express Server Raj es. The first lane, as Roberto already expected, is the required statement. Right. Const Express is equal to require express in order to use express, all you have to do is write this line. Const application is it will do express This express mattered creates an instance off express in the constant app so that AB is able to call upon basic express functionalities like routing with aware rendering starting your dynamic with bridges, etcetera. Now, if you remember with the http module when you created a server, you had to write separate. If it's blocks toe handle, eat in each individual road on also each individual s u dipping with, you know something similar here and express but it's gonna be in a much more clean away. Here's how right up dot kid and the stakes in the road For the moment, I'm gonna just stick with the route route forward slash, and it's gonna take a callback function with the request and the responses para meters. And here I'm gonna raid response. Don't send hello Express and finally you right up. Don't listen. 3000 now, If you started up using Nord and access it from the browser, you see the response that says Hello Express. Just know that you do not have to explicitly call the method rest our end or restored right head that is handled by express Internet E. It wants to be much more clear that if you try sending a Jason object, insert off just sending a string in the same function I risk dot sinned. And when a center Jason object that's his name is my name and age savored from the application again and in your browser called the App again, this gets you a Jason object that is automatically triggered by the closer as a Jason. Now, how did the brother no border if you inspect the content off the browser, bitch. Under the network section, you notice that the country type is automatically sent to application. Forward slash Jason, this is smartly done by express. Okay, you will see much more off express in the coming lectures. Hope you enjoyed this one. Thank you. 16. Express Serving Static HTML: you saw in the previous lectures that it is extremely easy to create a basic Web server using express. Also, if you remember your first project, you have to serve static html page based on a certain condition, we'll see how that can be easily done using express. You can refer to the documentation here for some more details at express jace dot com. So ask about this documentation. All you need to do to render static HTML is to write an app. Don't use function with the express. Start static territory. Let's do it. Create a new folder called Express Hyphen Static and go to the terminal and run NPM in it on the directory. Then go ahead and install Express. Once turned, copy the Web folder from the first project. After that, create a new file called Static Gorgeous. Andi In that fine require express and then declare a constant AB is equal to express. No, If you want to serve the static HTML page, all you need to do is write a line ab the use express, not static. Rupe, now expressed or static, is a building middleware function in express. We'll get to express middle shortly But for now, just understand that miller functions work in between. The time I request is received Onda responses sent back and it can be called using the AB audios method. Using the expressed our static function, you can expose whole directories containing HTML CSS images, etcetera that are essential to building your express application. Right up, not get. And we use the route from for now and the girl back takes request in response. Now all you need to do the render your static HTML is to write the line response, not send index Note html Right up, Doc, listen, give the port number as 3000. That's it. Go to your browser. Andi, reload the bitch. You're starting Finally served now the handle requests for the post within All you need to do is write a post with that handler AP not post. You could probably write the road for forward slash Welcome and the callback takes the request in the response and you're right. Response. Don't send you called Post That looked far simpler. You could also directly reference the file from your browser as in local host corner support number, forward slash index toward HTML. It's it. In the next lecture, you're going to learn about express routing. Hope you enjoyed this one. Thank you. 17. Express Routing: so far in the course you've seen and also worked alongside me to write basic hello World Express app that handle simple s UDP get matter and probably a couple of simple roads like the Rude Road or the Welcome Proud. You were also able to serve static HTML pages easily. What you did is you wrote something called a route handlers that handle it's UDP methods for every possible road or part that your application could be exposed to. Now. What this road handlers do is that they process the request when you played the response object and then send it back to the color. In this case, it's a Brazil. What you've seen so far is all simple rots. However, When you come across a P eyes, you would see more complex roads with something called road parameters. These are Rhodes that contained parameters on which you need to base your vote handler. It'll be far clearer with an example. Let's dive into it. Let's create an application that's gonna fetch a list of all available customers for a road forward slash customers. We need to write a rope handler for it that before that, let's create a simple list of customers. Ideally in the real world. This list would be in a database or something, but for simplicity will just create an array of customer objects and color customer list. It's gonna have to feels name and I d think about it. Customer list is the acquittal customer. One according name. It's customer one and ideas. One customer do. Has a name, customer do and I D to customer. Three. Has name is equal to customer tree and I d equal to dream. Now the rope handler for this would be up. Don't kid the Lotus forwards, like customers on the callback, takes requesting response objects. Response. Don't sing customers list. Save the file and around the application type. Norman static dot Js Norman is another way of starting up a North application. The only difference is that every time you change anything and save it in your application , nor more automatically picks up the change and restarts the application. It's just flustered. That's it. Open the browser and type. Local host couldn't get the port number for what's life customers. You would get the customer list. Nothing fancy here. You've done this before? No, if you want to get the details off a single customer. Given a customer, I d. It can be done by passing the I D in the You are, and that idea can be looked up with the request object and show you how that's done. You write another load handler for this road and give the road s customer or what? Slash colon customer I d. Internally, This gets translated into customer. I d. Is equal to value off the custom already in the callback function. Have requested response parameters and right response, not send request your parents save the file. Notice that Norman automatically restarts the application now in your browser. Type local host Colin Port number, forward slash customer for slash 123 and hit Enter. The parameters are displayed as us to Moretti's equal toe. 123 Now, in order to get the customer name corresponding to the I D. Only need to do is iterate through the airy and fetch it declare variable called customer name. I'm going to write a loop. I'm using the for loop here. Four Index in customers list if customers list index, not idee, is equal to request dot paradigms doored customer i d. Then customer name is equal to customers. List of index Don't name does the braces and finally responds Don't send type customer. I d. Request our problems dot customer i d has a name, customer name. That's it. Save it. And in your browser type local host will import number Customer For what? Slash one that returns the value off the customer name. Now, if you trike, i d 10 would obviously get undefined. We'll put the restart sent on the NFL's condition. And that should solve the problem, right? If customer name is not equal to undefined response towards sinned. Customer already has a name, customer name and it's type response, not send customer. I d. Requested problems with customer. 80 Does not exist. That's it. Reload the bitch and you should see the message. That's it for this lecture. Hope you enjoyed it. Thank you 18. Express Middleware: express middleware refers to a set of functions that have access to the request and the response. Objects and can manipulate them are perform some other logic. With the application receiving the request and sending back a response, it could be more than one function that acts as a middleware between the request and the response. These functions can be chained together in sequence, since every maneuver function has access to a function cord next that cause the next function in sequence, for example, that would be a logging with over first and then an authentication middleware before the responses sent out. The next function is used in such scenarios. In fact, we wanted to use the medieval function in the express static example. It was when you could abduct use, expressed our static with you, register a middle where using Abdul use and that with it does something we look at it with . Some examples now create a new folder in your workspace called Express. I find a little bit run in P a minute and then install express. I'm gonna create a new find call middleware gorgeous, and then first require express and then create a constant app. they said to an instance, Off Express. Now let's write a simple to load handler Abdullah Kit. Forward slash Welcome to the Rock. It takes the request of the response objects. And since welcome and right I broke. Listen for 3000 now start Nordmann, Middlebury Gorgeous. Open the brother and test it. You can see the worker message. Nothing Frenzy Next We right in the middle bit, as I mentioned earlier, has the ability to modify the request and the response objects. Let's see how after Jews, this is how you register in real bad. It takes three objects, the request responds, and the next function. Let's sit. Request Don't name, write your name and then call the function next. What we have done here is that we've created a name object inside off the request object that can be accessed ends. Well, we know where to find that out, Handler. To use this at the request of name, do the response write send and save it. Now refresh the page on the browser and you see your name here. You can also write made aware functions specific tow rope, the app produce function that you wrote here without a road Pigs The Rude road as the default job. To illustrate this, right, The Lord handler for the rood Rob Abduct kid prose Lesh The grist response to call back and it sends responds percent home bitch and also ever in their request Start name in your processor Goto local host 3000 It shows your name asset in the middle. Well, what this means is that the middle where is applicable to all the roads that start after the route route. Now, if you change the middle bit oharu forward slash Welcome. See what happens? The 1st 2 page at the root part you get undefined typos slash welcome and then you see your name. If you write the road handler for forward slash welcome for slash log in it would still be available. Also, the order in which you place these metal bar functions are important If you move the abarat use middle well down below the road handlers and then from the app, you'll get undefined values. Everyone, there are handlers also themselves middle way that have access to the next function. So instead of fighting the abduct use method for writing a middle way, you grows right it along with the road handler. Let's right around handle for the part forward slash Welcome forward slash log in. I don't get I wrote and right the middle bit that takes in the request response and the next this could be the logging were that logs every request that comes in Hey, response. Don't look looking and call the next minute. We're using the next function and then write another little well that takes in the rest request response and the next function. This could be the authentication with their type response. Don't Art sequel to authentication for the next election, and then you can call the last middleware function that sends the response and complete stir request response cycle. This response to insane It's sponsored. Look, bless Response Dirt Aunt No actors. The You are a new browser and you see that both logging and authentication or sure, the same functionality can also be written using the AB. Blood used function declare available for logging by logging is equal to function. That takes request response in the next objects and just says responsible log is equal to logging the next video aunt. Lastly, great abduct use for the same note called the logging and the Middle West. Save the file and we're on the road. It would give you the same result. Now, the abduct use is not specific to any http admitted it runs regardless off whether it's and it should be get or a post or a put or anything else. If you want some of the middle where to run specific to an http mother, then you need to add it to the world handler. But if you wanted to run regardless off the extruded committed, then you could just put it in the AB got used with. For example, if you want to run the authentication middleware only for the extra typical admitted, you can remove it from the abhorrent use and included in Abdur Get like this directed for this lecture. Hope you enjoyed it. 19. MongoDB Section Intro: so far in the course you have learned basic Norges and Express, you were able to create a Web server using express and add functionality used to it using express middleware in order to develop a full blown AB. More often than not, you will have to interact with some sort off a storage for persisting data. In this section, we will learn about Mongo DB. That is, by far the most popular database used in applications. Build with No Moncoutie Be is an open source document based no SQL database. If you have seen traditional databases or even Excel Sheet, you would know that the database contains tables with a certain number of columns. In definition, data gets filled. Row after drew into each of these columns. Mongo DB is more off a document based database, which is more of a container for a collection off documents. Usually there is no formal definition off the collection structure on like a traditional table with a fixed number of columns. Every document in the collection could have a different structure on a different set of values. Let's compare Mongo, DB and traditional databases, as you see here in a database in traditional art. IBMs are traditional relational database is a, well, a database. Among GDP, however, a table is a collection. Row is a document. A column is a field in a traditional table. You need a specification where you create table. But in Mongo DB, the document gets created the moment and insert operation is carried up. For example, in traditional table, you need to first specify the list of columns, their data types and so one and so forth. But in a Mongo DB database, you don't have to do that. There are many more comparisons on the space that give equivalence between the two. But essentially what this means is that a no SQL database like Mongo DB offers all of the functionalities that a traditional relational database offers. And in fact, a few more are focusing. The scores would be more towards working on the database using nor Js 20. MongoDB RoboMongo SetUp: it is begin by installing Mongo DB Open mongo DB is homepage and on the top right corner. You will find the link to download Mongo DB. Click on that and you'll be taken to Mongo DB. He's download center here. You see a number of choices for development on your laptop. You'll need to choose the community server. Click on there downloaded. It's a pretty basic installer, so just clicking a few next that each prompt would suffice. No. For longer debate to start, it needs a storage location to store all of its collections off documents. This can be created anywhere you warn. I'm gonna create a folder under the Norges Workspace and call it manga. Later in the command prompt, navigate to the part where manga debates installed and type mongo d don't xy double hyphen d Be part and give the folder part that you just created. You should see that the databases started, and it can be accessed at Port who. 7017 There's a default port for Mongo DB. You can also specify a different port with the double hyphen port option, but we just leave it at the default value for now Monger D is the Mongo DB Demon service or the server Mangalore E X E is the Mongol Shell or the database client using which you can create are modified documents and collections. Open another command prompt, navigate to the Mongo DB installation directory and run mongol dot e x e observed in the demon log that a new connection is established. You can also open more Mongol connections and see them all logged in the demon. Every Mongol connection automatically connects to or database called test. This can be ratified with the DB commanding the Mongol Shell. There's a whole list of commands that you can run like short debis. This will display the list of databases. Use DB with which to the Do you be specified. Currently, we're connected to the tester Davis. Now, if you're type short collections, there won't be any. You can create a collection easily an insult er document with just a single command. Db dot test not safe and specify a document When a type name some name. Now, if you see sure collections, it'll sure just if you're type David or test or fine, but you'll display all the documents available You can also insert more than one document using the insert. Many function for a given collection, right db dot test too dot insert many I'm going to give a list off documents here. Name is It was your name? One. It's one document. Another document with name is named two and another document with ideas. Anyone. This creates a collection called Test, too, and inserts three documents in it. Now that's for some basic understanding off Mongo DB. Aside from the shell, there's an easier way to interact with the database. Do I based DB Client called Robo Mongo? Open your browser. Goto Trouble mongo dot org Download Rob a Mongol. It's now called Robin Manga Treaty. After acquisition from three D software labs. Go ahead and install it. That should be straightforward. Once installed, open up rob among go three t and create a new connection. Give a name for the connection. Ensure that the port number is the same port number at which the Mongol server has started . Save it and click connect. As soon as you connect, you see that it has the best database having the collections that were created. Why are they Mongo ship You can also insert documents, view documents, delete them, drop collections and do many more operations. Every one of you a specific collection. Just double click on it and you will see all the documents in their collection. It executes the query command shown here. In our example, we created three documents using the insert. Many function from the shell. If you want to view only one with the name is named one. Then modify the quickie and write the name as name one within the find function. Then click the Run query button on the menu bar. That's it, and you will just see one document that you specify. Now that you have established a bit of a comfort level with manga, Devi was explore. Our note. App can interact with mongo db in the coming lectures. Hope you enjoyed this. Thank you. 21. MongoDB Using Native NodeJS Driver: in this lecture, you learn about accessing Mongo DB and working on the database using no jays. Mongo DB provides a native driver for this purpose on this beach mongo db don't get captured. I owe you Will see instructions to use the driver with Norges. Create a new project in your workspace and call it hello mongo, but on in B m in it except quality for values and then run NPM install mongo db That'll download monger to be package and at the dependency to the package store. Jason Fight. Once done, create a new file called DB claimed Dodges. Our objective is to interact with Mongol db using the Mongol Debian package The way to do this The first required the Mongol TV package and work the Mongol client class on it. So right Constant Mongol claimed is in Quito. We're inquired. Mongo db dot mongol claimed. Next, using the Mongol gland constant, you can either connect to a specific database or just coming to the port and then later on , connect to a specific database. So here's how it's done right. Mongol plaint dot connect and give the your less mongo db Cooler grew forward, slashes local host Colin 27017 Then the callback function takes two arguments. Error and the database client or the database connection. Let's handle the other first. If there is an editor, then just throw the error. If all goes well, then you could go ahead and gonna do any specific database. Let's go with test service type CONST DB Underscored test is equal toe. They be clint dot db off this, let's verify that by printing that to the concert type concerned Lord Log connected successfully did that date of his and up in the D B test dot database name? You could also try running the database functions on the object. Let's write one BB just George starts that takes in a function with entering the result as the bottom it is and type concert. Dark log db Stats, colon Jason dot string If I The result. Finally you close the connection with they declined dot clothes no. Go to the dominant and type no db client dodges. You should see the message that you got successfully connected to the database and you should also be able to see the database stats in the next picture. you will learn how to perform crowd operations on the database using the native driver Hope you enjoyed. Thank you. 22. MongoDB CRUD Operations: now that you have some basic idea as to how to connect do among the debris database, Let's run some crowd operations on it using the No Jay's native driver from Mongo DB before we start, crowd is short for Creator Tree Update and delete the operations that are run on the database. It's Mongol debate. Darkies first required the Mongo DB package. And under that, the Mongol gland class. We will explore all the Creator tree of great and village operations. Using an example, we'll connect to a new database that will go my diary. It's gonna have a correction with the name nodes. This collection is going to contain one note every day. Let's get started First will connect to the database type Mongol claimed Don't connect. Give the dude a busy water as mongo db Colon go forward, Slashes local host Colin to 7017 and the callback is gonna dig. Enter and the DB claimed next. I can't do the my daily database time. Const. My diet e school db is it will do they be blend. Don't they be off my dating in quotes? Then access the notes collection? No. Before that, I'd like to say that the my daily database and doesn't exist Since it is not present, the above line would create it Next. I'm const Notes. Underscore. Election is equal to my diet e on school db dot collection Off notes. Let's try inserting a document for today. A document in our case is a note. I'm gonna keep it simple for now. And just use the day off month to indicate a new note. So I'm gonna write Nords underscore collection. Don't insert one. Poof. The document is gonna contain the date, which will be new deep. Don't get admitted. And the notice learning one would be today the insert one function takes a call back as a perimeter that digs in an editor kind of result pedometers. So if there is an editor, then return console, not look and type. Enter inserting note. Do the database not case it is. My data underscore D B and also guns along the editor. There's a class called Jason built into the north core, and it has a function called string. If I it takes an object and converts it into a well inventor Jason Strength, let's use that to printer document that was inserted. So type concerned about log insert er document is Jason don't string you fight the result don't ops and lastly, let's close the plan connection using he be claimed dot close now open the dominant and never get to the static, re and run, nor crowd dodges. Now open Robo Bongo and refresh the data bases. You should see a new database by the name My Daddy and that a new notice inserted into the collection called Notes Next, Let's right There and Dream that can be done using the find function, as shown in the documentation find takes two arguments. One is equity and the other is an optional options. Let's write notes in the score collection I don't find and give. The Quid es did is new, did not get it and find returns, a cursed object that contains far too much information, then what we really need for our program. So what we do is we involved. The two are a function on it. It's a type dark to a that takes it a callback with an editor, and the result Let's call. The result is note today and again, if there's an better than through the error. If all goes well. Type concerned or drug found? No. And then Jason Dog String. If I note today, but string, if I function, you can give some additional barometers. That's going to tell the function how Maney cabs are. How many Indians has to be there when it's on words. The Jason object to a string. So in this case, I'm gonna give undefined as a second perimeter. And the last parameter is, too. Let's we could do intense. No again see with the vitals and on the terminal type nor card. Georges, you see a pretty Jason String pointed out here. If you want to see all the documents presented, a collection passed an empty object to the find function like this. Notes and score collection don't find and pass an empty object. Next, let's write updating a document operating a document can be done in more than one day. There's a function called find one in a player that finds and updates are document. In one single atomic action, we're gonna try a different method that uses the updated function. So what will try is will check if the length off the note today is zero. So what that means is it's the first note for the day. And so we're gonna inserted. If not, then where we loved it. Let's do that. So under the friend function time, if no today dot Lend is equal to zero. But the insert operation here and another else block, time concerned or log known for today already exists. So we are a breeding it and type notes in the score collection Dart Update one and give the query. Yes, did zinc will do? New dead Don't didn't did and then you write the update. US. Open curly braces, dollar sit. Clinton give the value as not learning one going to be today. There's so much more to learn, close to prices and next it's gonna dig, going back with better and the status of the up dude. So there's an editor as usual, we just throw the error. If things go well, time concerned or glogg matching regard count is status. Don't matched God. Another concern. Don't look updated. Regard count is status. Don't modified cold, and lastly, you close the connection. Save the vile and run it. You should see that the note already exists, and it is getting updated. But if I don't buy refreshing the collection in Robo Mongo. Lastly, we moved to the delete operation. Did. It can be done using when you must have guessed it LTD's again. Find one and delete that can find and delete a document in one atomic action. Or you could also just use the delete functions. Let's say for some reason that you don't want the North from yesterday, then in your court you can write notes and school collection, dot daily toe one and give the um either as deep new did don't get did minus one on the callback takes edl, and the result is better made us well. If there's an error through the error, things go well. Type console don't log. Deleted Record count. Yes. Result dot Deleted account. That's it. No, save the fight and good on it as no grand gorgeous. If there was a document inserted for yesterday, then you should see that it is deleted just a very further. You could remove the minus one and see if all documents for today are dilated. That's it. Now you know, basic read operations that can be done on mongo db using nodes. Native driver in the next lecture will be working on a little exercise when he would try to iron ore some of the most obvious logical issues that are in the application that you build now to see you there. No. 23. Diary App using Nodejs MongoDB: in this lecture will try to address some of the most obvious issues with the daily application that we created in the previous lecture, and we'll also try toe, make it better by making it more interactive. That is, taking in the notes from the command line. No first did on a few issues. For instance, all your notes are in one single collection, with each document pertaining to the day off the month. So once you have a note for the day of this month, it would not work for the same day of the next month. You may be able to insert another document with the date value, but you wouldn't know which month it corresponds to. Another obvious issue is that the object Cano over rates on the insert. Instead, the update just needs toe happened to the existing node. Lastly, the delete is always deleting the previous day snowed. This can be made more specific by giving the record that it needs to David. So here's a simple exercise for you to try. Create a new daily database. This is gonna have a collection with your name, and when you insert a new document, you will insert with the exact date and any updates to an existing note well up into the existing node. For the moment, do not worry about deleting any note. Pause the video and give it a try. Once done. 20 New with the lecture where I'm gonna show you how I would do it. Hope that was not difficult. All you need to do is change the name of the collection to reflect your name. The next change would be to change the date value and when changing toe coded string everywhere like this. Since you're operating the note for the day, you can remove the first part off the note, which is repeated instead. You can concurred in it with the existing note by writing notes today off zero dot no. Lastly, common dog. The delete functionality. That's it. No, run the court the first time it should insert the document. First of all, it needs to create a new collection with your name, and then you should see a document that is uncertain for today. Verify that we're going to rule Mongo and refresh the data base list and then view your collection, run it again and ensure that the notice of braided Indeed, no. Typically a daily or note taking app would not have static notes that are hard coded into the goal. But there would be some sort of user interaction with the user would enter notes and those would be stored in the daily. Other database will achieve that using MPM package yards, which we saw earlier in the course. Here's the second part of the exercise. Using dogs, take the north common as right, all deleted. If right is the command, then ensure that north Suffredin and if the lead is a command that ensure that there's a delete key like a date string. Once you do that, you can also extend it to view nodes, etcetera, positive video and give it a shot. Hope you were able to do that. First, install the Youngs package. Go to the terminal and time and BM install young eggs. Double hyphen. See once done back in your goal. Require the youngster package type CONST are agreed is in Quito required of your eggs in goods? Not agree. Then day if RG dot underscore off zero is equal to write, and our greedy dot note is not equal toe under fine, then modified the insert statement. Give the North s are agree dot note and also the updates Treatment where you happen. RG dot note to the existing note and finally, for the lead time. As if I agree. Don't and score of zero is equal to delete and our greed or did is not in Quito Undefined then notes on the score collection nor delayed one. Give the dead as our agree dot Did you can also extended to view all the notes type another as if our agree dog under score of zero is equal to view Notes underscore collection Don't find where did you the equity s and m dearly dot to hurry that digs, error and all notes the callback function and if there is an error then disclosed the connection time baby client dot clothes and then return consumed or log off better. If one goes well then concerned outlook are put All notes finally close the connection db client dark clothes Now if the commanders unrecognized then we send unknown command was the result and Prince will not long unknown command Sam define And when he does north daily dot Jesus and Let's try the right operation. Right? Give double hyphen not is equal to my first note. During this, multiple times will just abrade the note. You could also deleted using node David or Jesus. Delete double hyphen did. It's in Quito. Copy the date value from the date of this. Finally. What if I don't view functionality Type? No. Nor David Orgies view that you list all the documents. That's it. Now that you know mongo db interaction using the native driver in an extra lectures. Who would learn a very popular framework called mangoes that is used to interact with mongo database. And you would learn to build an FBI with Mongols and express hope you enjoyed this lecture . Thank you. 24. ES6 Promises: in this lecture, you're gonna learn about year six promises. The reason we waited this long to learn about promises is that it is used extensively in mongrels, which you're about to learn next. I'm not going to get into the argument off callbacks with his promises here, but would like to mention that the basic Prum eyes of introducing promises in Year six is that it is supposed to be a very powerful alternative callbacks. It is supposed to make the life of a programmer easier institutions where he needs to write a large number of nested callbacks leading to something called callback Help. A Promise is essentially an object that represents the eventual completion or failure off a certain a synchronous operation. Mostly when you're dealing with mongo DB among goes, he would be a consumer often already created promise that these frameworks have written in them. You don't have to create a new promise unless you need it specifically in application or in your FBI cope. However, we just proceed to look, I understand how a promise looks like so you have some manage off water does that you're consuming when you're working with these frameworks in terms of promises and how to deal with them. So if you go to this Mozilla page for promises, it gives you the basic structure of how a promise would be created. So promise can be created using a constructor like this, where promise, wherein you create a new promise with a function that takes in two callbacks again for results and reject. Let's were gonna create a new folder in your workspace and call it promises and that created a new file called promise dot Js. Now ask for the definition off a promise the executor needs to do something and then claim that the promise is fulfilled, meaning it is resort our needs to claim there it is unfulfilled, meaning that it is rejected. Engender a promise can have three states pending result or rejected as a basic example. Let's run this set time or function with one second Billy as the executors job. Go right, sit time up The goal Bank digs. Result Promise. Fulfilled is the message that the result ins and with a one second time out now this is the way you create a promise. No, let's consume the promise the way to consume promises type promise dot Then the den function takes two arguments called back for a success case and another for a failure. Guests. So then, say digs, call back with a message, then just on foot, consoled or log message on for the reject case that is the editor I consoled or log now, save, define and run the AB using No promise not Jace, and notice that the message is printed to the council. Now let's say you go back into the set time or function and insert off result. You say it's rejected, so type, reject, promise unfulfilled. Save the fine and grand again running This could print on Lady Unfulfilled section. Now the reason for the unfulfilled section getting printed out is that the time word for reject section got completed faster than the fulfill section. What this essentially means is there a promise can be either fulfilled that is result or rejected, meaning unfulfilled. It cannot be both. Now let us say for some reason, the functionality off the executor itself entered out. In this case, it can be processed using the catch function. So if I liked Jason got buzz, not a Jason, it was obviously through anything, we can let the ever beat room running the court. No, as Notre promised or Chase would throw the error and suspend all for the processing. Instead of that, we can catch it using the dark catch function. So remove the reject pile and only include the catch part type in dark catch error message is the callback and typing concerned about long exception occurred now running. This would print the council Lord log message and not the exception stack trace. Additionally, it does not prevent the application from executing further. Now that the EDL has been handed, you can further chain another then function to do something else. It's called Chaining Off Promises to demonstrate that Let's say you have a function toe to numbers function. Add a and me Jake if time off. Okay, triple equal do number and type off B triple equals two number we're doing Implicit me is stricter. Only numbers can be added. Now you can call that function with just changing to the previous then. So I've been don't then the function definition says concerned about log on one common do you could also change other than then and in this you to stipend concerned or log completed . My run. Now say we don't run and you will see all the results on the open With this basic understanding of promises, let us proceed to see how they can be used with mongo, DB and mongrels. 25. ES6 Promises with MongoDB: up until now, whenever you have written code to connect toe, a mobile TV database are perform operations on it. You've used Compaq's as that is what you're used to. Predominantly, most longer deep unity of driver functions Do return promises, however, since we've been using callbacks. Promises are not written, but in the absence off a callback function, these native driver functions Return promises before we dive into Among Goes in the next few lectures. I want you to get used to the idea off promises using Mongo db Native Driver. This would be more like a refresher on promises and also how to use it with riel packages quickly. Let's relight the same one. Good to be called using promises create a new file called Wango. Promise. Don't Jays now in the project run and B m in it except with default values. Andi run and being installed, Margaret. And be double hyphen save. Once done, you go to require the package. Diab Constant Const Mongol gland. I think we'll do Uruguay Mongo db Dark Mongol drained. Now let's look at the documentation for the connect Mental. This matter returns a promise in the absence off a callback function, so type well, connection promise is equal. Do Mongol claimed dot connect and give them mongo db You are Mongo DB Colon local host for 27017 You could also try to give forward slash test. Where we try to connect to the destitute of is Now, let's make use of this promise type connection promise dot Then now the result. Callback returns a database connection So DB claimed, is the bad omitted for the golf bag and in the callback definition, right const db underscored best is equal to be claimed. Don t be off test and then time concerned Outlook connected successfully through the database. Db on a school test dot database name again. You can run stats on the database, which returns a promise. So type DB on the score Test dart stance. No, since this returns a promise, you can use the dark, then on it dot then the result of returns. A stats object and contrite console dot log Give me studs Jason dot spring. If I stats and the other two parameters as undefined and to finally you can close the connection, we think they be client not close at the end off a doll, you can place a catch block that returns the editor with the rejected promise. Time don't catch. There's an better than concern, not log. Get him. Save the fight and running by using no Mongol promise Don't is so. This pretty much does the exact same thing, what you did in the Mongo DB introduction lecture. Except that it looks a little more structure with views off promises You can cry writing all of your good that you wrote for your daily Nords exercise as well. You will see that the Gord gets more structure and much more easier to read. In the next couple of lectures, you learn about using mongrels. That is a fairly popular podium used with mongo db so we'll see you there. 26. Mongoose Intro: so far in the previous lectures, he learned how to use long go deeply database. And I'm sure you've done really well in this lecture and a couple more relearning mongrels that is a fairly popular Orian based tool used to interact with mongo DB No, since you already have a good grasp in interacting with mongo db using the node.js native driver, you will ask Why use Mom goes, Let's find out. Try running your previous exercise with a blank note in this work and a blank loot. As insurgent, that is, you give the dead and then for the north you give a blank, will you? You can, of course, right, a condition in your gold for checking if the string length off the north is greater than zero, etcetera. But imagine that you have a database and a document, and that document has about 100 feels. And also, if you're writing an application with a fairly fixed set of phase, with each field mandating a certain set of properties to in present and writing validation , core for all that would be totally cumbersome. And that's when the naughty of base to like mangoes comes to the rescue mongooses. All the boilerplate scored to maintain connections, evaluating data of former times, etcetera, all of them in Bill. Essentially, it provides an object modelling environment that perhaps the Norges native driver for Mongo DB, its main USP is there. You can define scheme us for your collections, which are then enforced at the podium layer by mongrels, so you don't have to write specific validation, called etcetera, Longo's J is also has utilities for simplifying notes, callback patterns that make it easier to work with than the standard rival. Let's learn more off it with practice in the coming lectures, so you there. 27. Mongoose Note App: in this lecture, you're going to start working with mongrels. In order to start working with mongrels, you have to first import the package. First, let's go ahead and create a project called Mongrels. IPhone app. Once done, good determinant. Change the directory. Run in B m in it on it except all the default values and then run NPM. Install mongrels, No life and see once the packages in start in the project create a new file called APP Charges. Now that you have the package installed unit to require it in your application, right, const. Mongrels music will do recoil among those in courts. In addition to this, you can make moves. Use notes Defour promise slavery by writing the line. Mongrels dot promise is equal to Global Dog Promise one's done. You can connect to the database using the line, but connection is equal to mongrels. Don't connect and give the database you are, which is mongo. DB Golan. Go forward slashes local host 27017 forward slash test optionally. You can also check if the database connection went through or not. You can do that by invoking the owner and the ones mother so right. What D. B is equal to? Mongoose dot connection db dot on and, uh, concert goer entered your brain concern Connection error db dot Once open and give a function that just types consoled or drug we connected. You can also close the connection by writing baby dot clothes seem to fight and run it. If you've given all the perimeters corrected, the U. N, then we're connected. Should be printed out is you should see a connection error. What's done. You can start creating mortals using mongrels. After all, that's the main reason you're working with Mongols. No, every model is based on its chemo. A schema is like a set off rules that the data needs to abide by. If you're aware of examines key months, then you can relate. Better do it. You want to illustrate this with an example. Let's go back to our notes application and related using scheme us and mangoes. So here's how you create a schema. First time what schema is in Quito. Mongo Start schema. Then you create a schema for your notes. We're not schema is it will do new schema off now if you record your notes document had a date and also a node. The first Phyllis did, and the rules are it should be off type string required. True. And it has to be unique because every day you create a node and a single day cannot have multiple nodes. And a second feel this note which is off type string and required true. In addition to these, you can also create another field call updated. At a bit of that, it's gonna be off type did. Now all the types that you use here need to be in the permitted list of skimmer types and support the documentation on mongrels. Dargis Once the scheme is done, you can create a model. Why? No model is equal to Mongo. Start model. No note schema. Now, once the model is created, you can create new note objects that are here to the particular model. So I where note is equal to new nude model off did new did doored Those dates ring and the note is gonna be learning mongrels and the updated that is gonna be new. Dig. No. Writing to the database is accomplished by using the same metal. I note dot Save not to say meant it returns a promise, so you need to handle it. I don't then reserved, controlled all clog off result and then close the connection. Manga start connection dot clothes on the call boxes considered log connection closed. Now you can handle all the rejections and others in the catch block type. Don't catch enter considered log exception while saving the note and I've been the editor. Do it and then close the connection and suited earlier time. Mongu start connection. Don't close Considered log connection close to give the vile and running ones verify in Robot Mongo that you're noticed inserted now without making any changes. Run seem once again not is that you got an error that says a duplicate key insertion is a dumpling. This errors because in our skimmer we've defined the date field as a unique field. You could also try running good with an invalid day today, for example, for the updated at field. Just give any spring and not a did it was he that a validation and re strode. You could also give default values to certain feels in case it is missing, for example, with the abraded and feel you can give the default value as date got now. So each time something is updated to the note, the updated at field would get automatically updated. No, since you've given the default value, removed the value from the North, object Steve it and also delete the entry in the database and done it again, you should see your results on the console. You have seen a few renovations until now for a whole list of validations. The documentation is a great place to start here. You can see that you can mention minimum and maximum values for certain fields. You could also assign a fixed set of values. You can write functions that return something specific and a whole lot more One final thing before we move on to the next lecture our court. Here it looks a bit mixed up in sense that the data base models, bongos, connection and database operations are all in a single James fight. It is split up based on functionality, a bed so that it looks a lot cleaner and easier to read. Move the DB connection to a separate file, create a new folder in your project and call it D be and a new fight 100 corn mongrels dot Js copy based The required mongrels and DB Connection lanes to this fight. Also right model DOT Exports is in Quito BB. Next, create another folder called Morals, and under that create a file called Note. DOrtiz. Move the scheme and the North mortar lines to that fight again at the end. Right modules dot exports note model finally, in the abductees fight required those files Hi where D B is equal to required. Don't forward slash bebe forward slash mongrels and where no model is equal to require door forward slash models. Forward slash Note. That's it. Now try running your court once again and ensure that it still works as earlier. Okay, that's perfect. Now, in your main abdo TS file, you can run more database crowd operations. We just explored a few and then proceed to building your first AP with Express mongo DB and mangoes. You can try running no mortal dog. Fine. For the moment, you can give an empty object that returns a promise again. So type Don't then resigned concert don't long result and then catch for leaders with a dog catch a concert do drug. And you could also try a find by I d. I know model Don't find my i d Could be based the i d from the database. This again returns a promise the type dot then result concert or drug result. Let's run up. Did with him no modern dot Find one and updated Copy paste one of the data values from the database and give the note as learning mangoes. And it's going good. And again this returns a promise. So you type don't then present concerned or clog result. Okay, Now let's run the lab to find out if everything is okay, which it probably is. Okay, that looks just fine. Indented with this basically production and some hands on with monkeys will proceed to create your FBI losing express mongo, db and mangoes. So see you there. 28. Build API Customer Info: Let's start building a risk pressed FBI using express, mongo, DB and mangoes. Once done, will deploy toe Hiroko. We use express to create the server right Wilbur functions to read the input and render the response. And then we'll use mongo db to store the data and mongoose to model the litter and access it from Mongo to me. Let us create in FBI whose functionality will be do create customers, each with a unique I. D. Fish. Customer details from the decree based on the i D and ensure that only authorized customers are allowed. Access the a p A. Functionary in your workspace create a new folder called Customers Run INBio in it except for the default values and then NPM install express Mongo db Mongrels Boarding Parsa. Once done, go back to your folded and create two new folders Under there Baby and Murders. The DB folder will have a final call. Mang goes Dargis, and this is going to connect to a database. Corn customer in four models will have a file called customer dot Js. We'll have one morning for the moment for the basic details of the customer. The basic details will include customer. First name. Last name email. I d. Full number address on a unique customer. Ready? Mongols will help us do on the current operations. Pause the video and try out this part. It should be participated to the note app that was build. Okay, Hope you manage that. Here's how I would do it in the customer or Js file. First require all the models that will be used right? Const Bongos is it will do require among those Then we're schema is equal. Do Mang goes dark schema Then greet the customers Kema right customers Kema is it? Will do news came off the first fearless Heidi and we'll have it as a unique number for every new entry. So the diaper is gonna be number We're equate true, Unique. True. The next feel is going to be first name. This is gonna be a string and required feeling It's a time first name dying as a string required. It's true. Similarly, the last name type a string This need not be required. The next friend is evening And to ensure that no spaces are around the email You can include a trim through property and again this is unique. So day stream true, true Require it's true and unique is true The next field could be full Thank you this spring. True, True Require It's true. Next field address. Same scream required. True. Finally an update Time stop updated. And the score times time, which is gonna be off type did And let's give a default while you do it beat Don't know. No. The idea is something that the application assigns automatically for every customer. For that, I'm gonna use an NPM package called moment. He has a documentation footed moment is an NPM package that is mainly used for passing formatting and violating dates. In our case, I just be using it for busting. Run NPM in strong moment. See, Once done required in your fight. Const Moment is equal to require moment. Now for the I d field. I'm gonna assign a default value. Do it my before moment off. New dick dot four might. Mm. Is this s piss Where m m s? His assistance stands for minute, second and milliseconds. This is gonna ensure that this value is unique for every customer that this created. Okay, now that this key my is ready. We didn't create a model where customer is equal. Do Mongols dot mortal custom with customer kema and then type module Lord, exports is equal. Do customer now the Mongols orgies will remain same as the note application you build earlier. Except that in this case it's gonna connect to a database call customer in four. But const mangoes is in Quito. Require mongrels. Among those don't promise is equal to global Lord Promise then war db zinc will do mongrels dot connect and the water is gonna be monger db colon to forward slashes local host to 7017 forward slash customer in four. Finally right. More doing door exports is equal to DP Seem to file lastly, in the main folder create a file called server George Ace, This is going to say all the incoming requests first, let's require all packages that we need. Const Mongrels is equal to require mangoes. Const Express is it Will do require express const body parts, sir, is he Quito require Gardy I have been Barsa and then Bardi B is equal to required Dark was like dp forward slash among those about customer as he could do require dot forward slash models forward slash customer. Finally, where up is equal to express. And then we can also declare a poor what? Expresso, a two run time const. Or is equal to 3000 now. First, let's try to manually insert a customer object before exposing it as an FBI. Let's create a variable called John and John's the new customer, and we'll see if this gets inserted into the database. Okay, where John is equal to a new customer off first name. Sean. Last name Doh Amy is john dot doe at example dot com. Foon given number Andrew this tend Main Street, Columbus, Ohio, next city to the date of his type. Jon don't see you. And since this returns a promise, you got to consume it dot Then if it's a good result, then concerned or clock preserved dot catch, enter concerned, not log exception while saving note and when the other do it, try running the app. We should see a new document getting inserted into the database. Now let's see how we can expose this functionality as an FBI using express first. Let's right ab dot listen poured the callback Could great concern outlaw Express running on poor happened to poor number. Next, let's create a post road. Um, your post and the road is gonna be customer. But what slash create And the callback is gonna take request in response and said the response status as 200 restaurant status 200 not sink. Okay, now start the express up. Now, how do we call this so far? In some earlier examples, you've used the closer to call the express app. Here we'll use a software called Postman. Some people also prefer soapy. Why, it's just your preference for rest api eyes. I prefer post win. And for soap based services, I use soap. Ey don't know. Post me and install it. And once in start running hope it went well. No, I went to open Bousman, click on create a request and added to the collection. No, we'll just this basic act that were exposed using express enter. You are as http Colon, go with delicious local host Colon Give the port number Po's life customer forward slash cleared Select the deter Toby application forward slash Jason now create a Jason data in the body. I'm gonna have it pretty much same as what we inserted earlier in the APP. Click send. You've been a response. That this on. Okay, now let's build upon it. We'll make use off the package. Body parcel for this. If you look at the documentation, it is a model that passes incoming data in a middle way and then puts that past data into request. Dark body. We make use off body parts of our Jason function for this, right? I am not used Body Parcel Dart. Jason. This puts the Jason string as a Jason object under the request body. And this middle way runs for all roads and all extra dp mud. It's another route handler. Now you can create the object where John is in Quito. New customer off request start body. And then when you say we to the date of this internal just writing a concerned or log, you also write response towards ST off result. And when there's an editor, you see rest dog students 400 god sent save the file and run the load from postman. The first time you run, you get the response back. And the second time you run the same data you get a new plea for murder. Jason Ader with proper description of the other that you try to enter a duplicate i d. One last thing Instead of having John as the variable, have a more generic name like customer, You could also have lunch for getting a list of all the customer center in the database, or find just one customer by his or her i D. And also one drought for operating here. First, I'm gonna create around for the Sud Be jet matter. I don't get forward slash customers. This is going to get all the customers in the callback type customer don't find and given empty Jason object dark Then if all goes well, rest your status. 200 send resumed. Don't catch if it results in an error and restaurants status off 400 not send Editor You can write another road to get customer by i d The right Abdullah Kid forwards life customer over slash colon i d The callback takes requesting response objects and that you write customer don't find one and the object can be given us i. D. S request dot arum's dot Heidi dot Then result responses are straight. This 200 dots sent present. Good catch. Enter responsible. Stratus off 400 dot ST Adam. Now they want to update existing entries in the database. You could create a role for the STT. Catchment it right after that batch over slash customer, forward slash I d and the callback takes request in response objects. Now, since it is an update, we need to update the time stamp. If you do not operate, the timestamp manually are in the route. It's gonna get updated because you've given a default value. When you declare this came up or when you defined this came up, I request dark body. Don't updating the school name stem is equal to do did dot no customer. Don't find one and update Do the I. D. S. Request our bottom start already and a digit with the new request Start body that also has an update. Timestamp dark then reserved restaurant Stratus 200 Send result in case of an editor toward catch Better response your status 400 not send Aaron. We could keep writing more roads, but I guess you get the idea. You could define as many adults as you want, depending on the functionality and define water. Go for requests on each rob. Now, with this in place, let's run a few tests to ensure that we have a working application on Bousman. Let's try again. EST really be mother. Give the You are less extra DB Golden local host 3000 forward slash customers and now clicks. And if you see the list of customers that were created next, let's try the get customer by ideas. Rob Give the You are less local Host Gun 3000 who would slash store forwards life Give the I D Good. This works is when Finally, let's try to update an existing I d. Change the history. Be matter to batch and change the body application for it slash Jason. Now copy the request body here, change the name could John Doe senior and then clicks in. Now you should see a good response back. Now go to the database and verify that the document is in fact a braided. Okay, not with the A P. A. Really, A next step is to authenticate the users off this AP I Obviously you don't want complete access toe everyone to view your customer Didion's or even worse. Update their end up in the next picture. You're gonna learn how to authenticate your FBI using hashing on Jason with Goggans to see you there. 29. API Authentication Password Hashing: In the next couple of lectures, you will learn how to authenticate your FBI. A very popular authentication mechanism is by using tokens. Tokens typically looked like a big string. With all random characters put together, However, these are pretty much an encrypted version off your password. On another secret code, all major players in the FBI ecosystem use token based authentication. For example, Google, Twitter, Facebook Get up, etcetera. Earlier to the broken system, whenever a user lock in his station authentication status, everything had to be maintained on the server and for all further transactions off the user . The server validated this information, which meant a lot of server overhead. Duncan system came around wherein anytime I using logged in, a token was sent to him or her. It was then up to the claimed to store this authentication token and send it across to the server for every future transaction. This way, the server did not have to manage authentication details as heavily as it did earlier. Okay, now coming to adding authentication to your FBI, The first thing is, our customer details don't have a password field. Let's first created. So under the email, Phil, create a password field, which is off type string Andi require is true. Next, we can create a customer with an enemy on the bus word. However, it is well known that you're not supposed to store passwords in plain text format in any server, however, secured the service. Typically, a one way hashing algorithm is used in orderto hash the password before storing it in the database, we'll be using a package called Big Group in orderto hash. The password. Here's a documentation for big Grip on NPM. B Group has a number of functions. Toe hash the passport. If you look at the recommended usage, be kept dark hash. It takes three arguments, one a plain text, passwords, another sorry groans and her a callback function. Santon's typically indicate the complexity and the depth of the hash, so they hired the number. But the salt on, the more difficult it is to break the hash. No back in your terminal. Install the big clip module using NPM install be gripped, double hyphens, say, and once done, require that in your Salvador DS file as constant decrypt. Is it going to require bigger? So now in the customer over slash create road at the lane. The group don't hash the request. Nobody not password and give the soul tones instant. And in the callback. How edit. And they hashed password as arguments and then said Customer dark Password is in Quito. Hashed password. Now start the 70 was ignored or more money. And now investment. Give the fields and then send a request. The response shows the hashed password is inserted. Okay, this just complete Step one off authentication. In the next lecture, you're gonna learn about Jason Webb Dugan's. 30. API Authentication JWT: In the previous lecture, you learned how to hash passwords before story. Get into the database. Once a customer is created, he's an authorized user. Since Ali Bey eyes are http based, there is no way for the server to remember which user is logged in and Israeli requesting data are updating data. And with each request, the user cannot be asked for a user name and password. It would be quite annoying to the user on this extremely bad design. This means that there has to be some information sent from the user that indicates that he or she is the authorized user, without really passing the credentials in the request every time now, this problem can be solved by using a token exchange mechanism where the server generates a token and hands it to the client. At the time of the first logging, the stoker needs to remained in by the client and sent across to the server that every request he subsequently makes. This token creation and validation at the server is done using Jessel Web took. If you look at the website for J. W. D, it describes what it is. The scenarios, which basically is authentication where it is used that we try to help you understand all this by implementing Jada Beauty in our own customer. FBI? No, in the dominant First install the MPM package. Jason, we're talking using N b m Install Jason Webb Token double hyphen. See Next up. Require it in the server nor GS fight as Const. Jada Beauty is equal to acquire Jason Webb Talking using Jayla Beauty are so I wouldn't estrogen greater token and send it back to the customer. Our objective is to return this token to a customer of one registration. The customer needs to store the stroke in somewhere. And for every subsequent request that is made, it is to send the struggle. If the Dugan gets a very frank, he be granted access else. No. Here on the get her page for JWT, you see the usage. The user credentials can be signed using simple jailer beauty dart sine function. This function takes three arguments. The 1st 1 being the object that needs to be signed are encrypted. The second perimeter is a secret key. It could be anything from a simple string to another city read from a fight. The last perimeter is the callback function that returns the better or the Jason Webb broken. It's a Let's implement this first in our server. Georgie s fine. Once you add the customer to the database, generate the token and send it back to the color. So I response dot Jason, send a Jason object. It says status is success. The second field is tokcan, which, as jwt not sane. Off passages. An object here in May is customer door in May, and password is customer door possible. And then the secret key is gonna be a simple string like ABC 123 You can use a better key than this one if you like just this in postman. But before that, delete the customer and Roma Mongo and run the create customer request Once again. What you see in the response is the web Tokcan. Now going back to the jwt dot io page scrawled on the Jason worked open structure. See that? It consists off three parts. The header, The payload on the signature. In order to be called the signature, you can use the debunker on jwt dot io bitch now in the d burger copy paste the broken that you got from the north FBI. Immediately the three right boxes get updated with values that you give for signing. However, noticed that the signature verification has failed. This is going to succeed only if you give the secret. In our case, it was a B C 123 Now see that the signature is very fight. We got them to do the exact same thing using the JWT, not verify function. As you see in the documentation that s interests abortion, pigs, three arguments the token, the secret key and a callback function. First, I'm gonna implement the verification steps in the forward slash customers wrote that gets all available customers. All you need to do is wrap the existing functionality with the JWT door. Very fine, mother. Let's do it. Going back to silver don't genius fight right jwt dot Verify request Dodd header And we're gonna put the token in a field in the header coiled X iPhone art. And then we're gonna pass the secret, which is a B c 123 and then the callback function that digs Edin and the D quartered stream as bad a meters. If there was an edit, then respond with status 400. Don't send off better as meaning If the token was decoded and verified, using the secret to given. Only then you can try other things in our guests. It's customer doorframe. Where you gonna bust the empty Eddie and Redonda result? Save it? No. In your dominant start, Sir Edward or genius and once Express has started listening on the poor. Open a postman and in the get forward slash customers road under the header section on a field Corn, eggs, hyphen aught copy paste the token that you got from the customer Create robe. Once done, click saying, See that the customers list is finished. No, this verification needs to be done for every road here after so instead of writing the same verification logic for every load, you can define a method to do it. In the longest documentation. You see two kinds of methods that can be defined in this chemo instance minutes and static methods, methods that are called from instances off the model. Our instance meant it's and static methods are those that can be called directly from the model itself. In our case, during the customer creation process. We create a new customer instance. Hence we need an instance matter. And during the verification process, we don't need a new instance. So a static method will suffice. So in the customer, Nagi is fine. We're gonna create a method in the customer schema. But before that, make sure that you required JWT that so right const JWT is equal to inquire. Jason were Dugan then type customers Chema dog methods don't gen dri JWT token isn't will do function. It takes a callback function inspire omitted. Could be the entire functionality written for this road here. Since this is an instance method, we use the this keyword to refer to the customer instance that called the Smith. So it's gonna be be kept dot hash this dark past where and that set this start password is equal to hashed password, Then change in tow. This dog saying lastly in the place off response, sir Jason called the callback function with the status and the judo Flutie took So replace restaurant Jason with Colback and in case often better called the callback function with 30 days callback status as editor and enter tedious food is gonna couldn t the actual No, back the server. Georgie s fight. All you need to do here is called the gentry JWT Token function. So type customer Dodd generated JWT token and the gold back. It's resent this perimeter and if result door status is equal to success, then respond with rest. Dog Jason Off result is rest Dodd Students off 400 don't send result dot error d days Now the token generation has been moved to a common method. Now we need to move the verification for all roads to a common function in short of writing it for every wrote that could be done using a static function. So under the customer, gorgeous fight right customers kema. But don't start ICS Don't verify JWT talking is in Quito function. This takes a token as an argument Create a variable toe, hold the decoded object under the function, open a trade bloc and verified the token with the secret I D quarter is equal. Do JW dedo verify off Broken with a secret a B c 123 Next, we will return a promise from this function. If the d chord worked a bill then return promise start result off decoder in the catch Block. Cash off. Enter if something is real, we returned the error as a promise. Rejection Return Promise. Don't reject off, Aaron. Now back this Howard RGs file. You need to wrap them, get functionality with a verify JWT token function. So right customer dot Verify jade ability talking and give the battle me dress. Request dog header off X hyphen aught. Now, since this returns and promise type dot then result We could return the result of the find function so that we can easily change promises and have just one catch functionality in case something fates type return customer don't find, Then you can Jane promises returned by the find function save both defines find open postman Desta functionality. I just played one more customer entry change the emails do jane dot doe at example dot com Now you get another token to use. This are the earlier token. It doesn't matter in order. Destiny The roads? No. When the token and the get over slash customers wrote request you get the response back now Change the secret key in the customer. Georgie s fine. You could change it to something like every C 1234 and then save the fight. Now on the get forward slash customers wrote again and see the other. Now that we know this works, you can add the same kind of functionality toe all of the gloves for updating are getting a customer by i d. So in the Abdul, get round handler Time customer or verify JWT token off the quest header Ex Ivan aunt Then result even return customer Don't find one off Heidi. Is it going to request our problems for 90? Since this returns a promise the previous court works with and the same holds good 40 but the update. But that is well so right Customer, Don't verify Cheetah beauty Token off request for headers of X even aunt don't Then result Quist or body Your update on school Timestamp is deed now and return customer don't find women updated now that again returns across So the previous core or it's good. Now go back to Grossman and for these roads I'm the token trying to find one minute. See that you get a response back and also tried out for the batch. Metin, you could also try giving the wrong token and observe the different messages that jade ability throws back. One important thing is that there are multiple ways off accomplishing the same result. For example, for example, by defining the generated JWT token on verify JWT token methods as middleware, or by defining a measure where function toe call the very fighter committed for every load and more such different base. Feel free to explore all of those ways of achieving this functionality as well. Remember, the only way you're gonna master anything is by trying different ways. Failing that, it may times and then succeeding that completes your FBI with authentication. Hope you enjoyed it. 31. Adding Customer API to GitHub: now that you have big tearfully. Fortunately, FBI with authentication. It has deployed to Hiroko so that it is accessible over the Web rather than accessing it as a local application. Every time before you deploy, I want to introduce you to a very popular distributed washing control tool called Get. For those of you who need to know what is version control, it is a system that is used to track history off a collection of fights. Usually it will be so school. Every worship captures snapshot off these files at that point in time and it to store in a specific location called a repository. The abortion control system captures the changes. Who made the changes on when, along with some details regarding why it was made? A local washing control system are a central washing control system, usually captures changes on a computer or on a server, respectively. In a distributed abortion control system, the full repositories recites both on the developer as well as in the central hub, so developers can work on the goal at the same time and later sync it with a central repository so that there's no lock or situation for any developer now coming back to get it is free and open. Source. It is also very easy to learn has both Georg based tools as the last command line access to the repository. First, let us set up your account on ghetto. Open your Brozi and go to get hub dot com. The landing paid of data shows sign of duties. Enter your user name, password and email and say no once. Don't try signing it with the newly created Grinches for your account. Once you log in on like my good have account or to see here, you would not see any repositories as yours would be a fresh account next that is installed . Get if you're in Windows, then Goto did for Windows, not kid. Abduct io on your brother. Click on W. Was the video and install. Get following the instructions and accept all the default options during installation. If you're on a Mac, then goto get happen. SCM dot com Always last download forward slash mac, download the package and follow the installation instructions. Okay, Hope it went well in order to verify installation. Opened the git bash that got installed are open a command window and type Get double hyphen washing. This should list the washing of get there Got installed on your computer. Now you can start adding fines to your guitar, become open the command drunk and navigate to the customer FBI territory that you bring just now. Now, before running any common. Since it is the first time that you're running any good common on the system, you can use the get conflict command. I get contrary a life in global user dot name, give you a name and then get conflict double hyphen global user dot email and give you an email. Eddie, next time, get in it and this should be typed on the directory where you have written your customer FBI this initial I just get on your directory and it creates a dark kid belfry inside off your project. The countries should not be changed. Now that good has initialized. Start adding your friends to begin staging area. He was in the combined get ad dot If you don't need any specific files or folders to be on get, you can move it out of the gate staging area by using the gift. IPhone are, um, command in our case, we don't really need the NPR models folder, Toby added together. The reason is that it doesn't really constitute your core application and is already listed in your package tour. Jason, fight as dependencies. Just running NPM install before running your will automatically download all the dependencies. Let me show you real quick on the hello Express. I'm gonna delete the note. Underscore Models folder. Now, if I tried to run express, it's got throwing error. That express model is missing. Next, I'm gonna run npm install and notice that the node moderns folder is regenerated. I'm gonna distance running known Hello expressed RGs And it works. No, back to get in order. Forget toe, not add a folder. Or, if I insert off doing a good I've been Adam every time you can add a cost If I called Dr Ignore, This file contains a list off everything that you want get to ignore. So in the root off your project on a fighting corn dot get signal and in its condoms forward slash nor and score models no type get status and it shows all the untracked files . Add them to get using get add dot and finally coming. Just the repository using the get from it comin. Now it's your type. Get status. It would show that all the files on the folders are added to the dick. Abortion control. Now you have added on the fines and four days to your local git repository. The next step is to push your repository the central get help. Not going to have you double gold. Click New repository. Happen the name off. Your FBI ended her description and click. Create repository. Get up Gives you all the commands required to set it up. Now, we have already created a repository on our computer. So we just need the last two commands here to push it. Took it home. Copy Lose. I get removed. This command tells Get on your computer the location off the remote repository and also names it as origin. Next time. Good Bush origin Master, This which is the repository on your computer? The get habitable difference to buy origin and it pushes to the branch called Master. Now let's go back to get him on. Refresh the beach and you see your repository There. In the next lecture you will create a hero who account and deploy our app. There 32. API Deployment to Heroku: in this lecture, you will learn to deploy your application on Hiroko as a prerequisite. You need to be conversant with the good comments that you saw in the previous lecture. First of all, Haruko is a cloud passed, provided or a platform as a service provider, where you can deploy, run and manage applications that you might have built using, nor Jace bite on Ruby. And many more in our case will be deploying your FBI building. Norges on your brother. Goto Roku dot com If you don't have an account, please Creator, if you already haven't gone, log in using those credentials. Once you're Logan locals, dashboard appears on the right hand side, you see a button to create a new app or a new pipeline clicking on it. You can give a name for your app. If it is available, it can be created on herbal. However, you will be doing everything from the command line in the scores, so do not worry about it Now. In order to access documentation on how you can deploy the various methods off the ab, R a p a deployment etcetera, you can click the link here in our case we are interested in deploying God nor Jesus. This opens up a ton of documentation on Norges and what you can do here on Hiroko the first thing is in order deploy your app where the command line You need Hiroko's command line interface in start. So under the deploying with get section scroll down to download Hiroko's Ciel ailing are just Google Download and install it. The installer are automatically adds Hiroko to the system environment part variable once you're done cheaply. So if you open a command window and type Hiroko hyphen B, it lists the heroic abortion and also the North abortion it comes with now in the command line. Change to the directory off your FBI log in to Hiroko where the command line using Hiroko logging. And here, Roy, you're used already and password Next. In order to create an app type, better go green. This will create an app with a random name. You can verify that we're going back to the dashboard on Perego. Now that you have created an app, the next step would be to just push your FBI Haruko and see it working Well, not just yet. We have a few more stuff to take care off before we deploy toe. Hiroko. First we need a mongo DB database that r a p a talks to on your local system. You had a local monger to be installation with which your epi I was interacting for that local provides are done off Adams, one of them being M labs mongo db. In order to install, I don't have to provide some billing information. That is your correct card details. But don't worry, you won't be charged a time because we'll install only free ones here. It is just needed for completion purpose. No. Once you have entered your credit card details, you can install the free. I don't By installing this free adult, you can have your database that Norges can connect to will install it using the heroic Aussie ally. I run this coming to install the owner Hiroko Arrogance Colin, create space more lab. Normally, you can just run this command and it works. However, you can also provide additional options like the app that you want this installed for. For example, you can just give your app name giving double hyphen, followed by the APP name installing this adult creates a conflict variable in Hiroko called mongo db underscore You are. You can get it using Hiroko conflict. Colin, get mongo db underscore You want it now? Since this is exposed as an environment variable, you can access it in your application as process dot e and b dot mongo db On the score you are So now in your mongrels. Jeers Fight. Replace the local host data Busy Worry with this one where DP mongers don't connect and give process dot envy dot more. Would he be underscored? You are one more thing at the moment you might have hard coded the port number to be 3000 or 3001 or something else that is available on your local computer. However, this sport might not be available on hero. So for this purpose, Haruko exposes another environment variable called board on this very well can again be active test process that e and P dark or so in your service charges filed changed the hard court or two const. Report is in Quito process dot e and we don't port What, 3000. So what This does. Is it your first check if the heroic report is available. So if you're running on your local computer, this environment variable would not be available. So the value of port would be a hard quartered value that you have given which is 3000. And on Hiroko it will take the value that comes with process, not envy dot That's it. Your app is now ready to be deployed first will push your repository changes to get I get status. This shows all the fights that have changed since the last coming. You can add and covered them together with the get command Get come It have been you and give the common best setting up for deployment on Hiroko Finally deployed a group type Get bush Hiroko Master, Once you see a success message, go to your dashboard on Hiroko. Think on your app. I know the right Say click more and select view logs. It would show that your app has started. That's it. Your app is now live in production. Now if you want to test it, open postman on another. Create customer request. Replace the local host Colin pork number with Hiroko application link next sent and you see a response with a token number. Now you can copy this token and placed it in the get customers request under headers. Also, replace the host Colin poor to the heroic Oh, application link extent and you see the customer that you just created. That is really great. Now, if you want to see the database and police were robo mongo, you can do that too. Just i Roku conflict and gives the mongo db. You are right. It would be structured us monger. T p colon go forward slashes user name Colon. Plus, we're at the rate host name calling poor for what's life date of his name. Usually the database name is the same as the user name. I'm gonna go with these values and best to the connection once. Now, is the distance successful? I'm going to save the connection and then connect to it. Now, just expand the database to view the collections. And there you see the customers collection with documents in it. That's it. So to summarize what you did, you build an FBI with Jason Webb tokens and hashing for security. You tested it on your local computer and then install git and pushed it to the remote repository as part off washing control. Next you installed Hello, Gussie Ally. And in your project directory, you created a new Hiroko application using Hiroko create That creates a new get remote called logo. And next, you modified some of the features off your application to make it. Hello. Compatible The first of them Waas the Mongo db You are right for which you install M lab. And next you ordered the port number to use the one on Perego. And as the last step, you pushed the changes to get and Hiroko Master Branch to complete the deployment on Dusted for its functionality. Congratulations on taking your FBI light and function. That's it for this lecture. Hope you enjoyed it. Thank you.