Learn Mongoose - A NoSQL ODM | The Best Way to Write MongoDB Queries in NodeJS

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello hello and welcome back to the immigrant programmers channel my name is kritika and if you're a new viewer you won't notice anything different but our old subscribers and old viewers you must notice something different in our studio so this is our new temporary studio because we just moved into a new house our house and we need to change a lot of stuff we need to do a lot of uh revamping so for now bear with the studio so coming back to the topic this video is the fourth video in my series of orm so so far i've just covered sql based orms and in this video i'm going to do something different so i'm going to cover a nosql orm so which is the orm for database known as mongmoose so it's a very easy to understand straightforward and a schema based on where you define different schemas for your collections and uh it's easy to insert documents as well so and if you don't know the lingo so far don't worry we're going to use the same language saint jordan twelve the video and i'm gonna explain you what each of these terms mean and if you don't know what orms are and if you're directly watching this video in my rm series and you want to check out like different sql-based urls i've covered in the past go check the different videos the link will be down in the description below and you might also be seeing the links flashing here so go check them out um but before watch this video till the end so in this video as well i'm gonna use the same structure that i've been following in my previous orm videos so i'm going to have two collections the customer and the order collection and the customer and the order collection are connected to each other associated to each other by a one-to-many relationship so uh one customer can have many orders okay so without any further ado let's get coding okay so as usual i already have the project structure set up so that we don't waste any time on the less important things and just focus on the more important things at hand now in this video we're going to use a nosql database and the database is mongodb so we're going to use an orm to access that database which is called as mongoose so first things first we need to install the mongoose package so for that you just go npmi or npm install whatever you prefer and then you type the name of the package which is mongoose go ahead and hit enter i already have it so i'm not going to do it so once you have this package installed we will be good to go okay so now that we have the mongoose package the first step would be to establish a database connection so to do this i'm gonna run the mongodb in my local server so like on the local host so i just require the mongoose package here and i create a connection by just calling the create connection method on the mongoose package and providing the url for my local database so as you can see my mongodb server is running on my local host at this port and this is the name of the database so whenever you run the script for the first time the database is going to be created by mongoose automatically so you don't have to worry about that so here i'm just going to export my connection object so i can use it later while accessing the database and performing some queries all right so another thing that you need to take care of is since i'm running mongodb on my localhost i have to make sure that i already have installed in my computer so in order to do that you just go on google and say install db on mac so because i'm using a mac mirror here i'm going to show you the steps for mac you can do the same for windows just type install mongodb on windows and you're gonna get the first link here for mac os and this is the official link from mongodb so um i'm just gonna go here and follow the steps so you install xcode first and then you use brew to install mongodb here so once you do all these steps just make sure that you are you are running the server by just opening your terminal and just write once you do that you it's going to take you to the shell and now you can perform mongodb queries locally for example i will just do this show dbs so it's going to show all the databases that i have locally um this case your database is already created by mongoose when i one when i ran the script for the first time so i did not create it and you don't have to either we'll see how to do that all right so once you make sure that you have installed and it's running in your local server you will be good to go all right so now it's time to define collections or what you will call tables in sql language so first of all i'm going to define the customer collection so in my customer collection i have two fields the first is name and the second is email but in order to define the customer connect collection what i would do it i'm going to require the mongoose package and also the connection i'm going to require the connection object that i created in the last step and now you define the collection by just using the schema class or the schema constructor on your mongoose package so by and also by using the new keyword because we're defining a new schema so we're telling mongoose what our customer collection will look like and what fields it will have what would be the type of those fields if they will be required and stuff like that so let's see customer object will now be an instance of my schema here my mango schema and it's going to take an object and inside that object we're going to pass different fields that my customer collection is going to have so for example my customer collection has a name and it has an email so the name the type for the name is string it's a required field so we it's like a compulsory field we cannot leave it blank the email field similarly is a type string as well and it's a required field as well so these are the two fields in my customer collection now i'm gonna just call the model method on my connection object and pass my collection schema so pass my customer schema right here and tell mongoose that this is one of my models so if you've seen my previous videos on oran they're all about sql based orms but something common is that we always use the model method to define the model or the table uh using the orn so this is very similar to what we did here we use the model method on the connection object and we pass the schema that we defined in the previous step here and we're basically telling mongoose that this is what my collection looks like these are the fields of my collection and consider it as a model so we're telling mongoose that we're ready with our first collection the customer collection and the next thing would be to export this collection so that we can use it later on while creating the database okay so once we have a customer collection set up we're gonna do the next one which is the order selection so in order to do that we're gonna do we're gonna follow the same steps so we want to require the mongoose package we want to require the connection object and also the customer collection or the customer model we're going to require the customer model as well because we have a relationship between our audience collection and our customer collection and the relationship is that one customer can have many orders so basically um one-to-many relationship so we're gonna define that let's see how we can define that using mumbles all right so in order to define the schema for the order collection we're going to do um we're going to create a new instance of the mango schema and name it order it will have two fields the first field would be the total purchase price so basically the total and the next field is the customer id so this is basically a foreign key and as you can see we're going to define the type which is object id because here the object id of our customer so basically the id of our customer that we don't define it's like by default uh field that you're gonna get in all the databases so the id field so um we're gonna we're gonna associate this id field of the customer with the customer underscore id field of the orders collection so that's why you see type is object id because by default uh the type of id in mongoose is object id so now we provide the reference and the reference is that it's associated or like it's it has a relationship with the customer collection so that's what we put here customer it's a required field as well and we're going to create the index here so you can you can set index to true false or just skip this field it's like an optional parameter but i want to do a lot of searches based on my customer underscore id value so that's why i created it to be an index so that my searches are efficient so um also the total field is a type number and it's required as well so these are the two different fields in my order collection and now i'm gonna define i'm gonna just create the model and i'm going to call it order and i'm going to pass my collection here that said that's all it's the same step that we did for the customer collection and now we're going to export the order collection as well because we're going to use it to query the database all right so that was straightforward we've defined both our collections our customer collection and the order collection and we've also defined the relationship between them and as you must have noticed in mongoose we did not care to define the kind of relationship that exists between our customer collection and our order collection so if you've seen um again like i'm saying this again but like if you've seen my older videos on like my previous videos on different kinds of orange we always define the type of relationship between the two collections if it's a one-to-many relationship many to one many too many whatever we define the kind of relationship as well but here in mongoose we did not define the kind of relationship does not care about that we just defined the reference we just told mongoose that my orders collection is connected is is associated with another collection and the name of that collection is customer that's it that's all it doesn't care about what kind of relationship exists between them all right now that we've established a connection with our mongodb we have defined both our collections now it's time to move on to the most interesting part we're going to query the database so we're going to perform different kinds of queries we're going to do insertions deletion and search and also insertion with foreign key all right so um are you excited i'm really excited okay so we're going to do the queries in our index.js file i'm gonna require my customer collection and my order collection okay so first of all let's insert some documents inside our customers collection and if you are not yet familiar with the mongol lingo oh it rhymes monolingual a lot so let me tell you what you would call a table in sql-based databases you're gonna call collections in and also each row inside the table is represented by a document in mango so for example each collection can have multiple documents similarly each table can have multiple rows right and each row inside a table can have different values for different columns right so similarly each document will have different values for different fields and each document will have like all the fields that we define in our schema so basically each collection is a collection of different documents all right so as i mentioned let's insert some documents in our customer collection okay but wait before that let me tell you something really very important if you want to connect to your mongodb locally you can use a tool called mongodb compass so um let me show you how you can get it you just go on the internet and say mongodb compass install and i think it will be the first link so you can just go there it's an official mongodb and you can go and follow the steps for windows macos and linux and you can install mongodb compass i already have it let me show you how it looks like it looks like this mongodb compass and this is already set up but since it's a video where you learn everything from scratch it's my duty to show you if you open a new window so um i will just quit this and if i open mongodb compass for the first time let me show you how you can set it up so this is going to take some time it's going to load all the plugins okay so this is the first page that you're going to see as soon as you install mongodb compass on your computer or your laptops or wherever so what you want to do is you want to start a new connection so either you can paste the connection string of your database but what i'm going to do is i'm going to click here fill in connection fields individually and since my connection my database is on the local host you're good with the default parameters so don't touch anything don't uh you don't need to feel like anything anywhere because it's going to connect your local host to seven at the port two seven zero one seven which is the default port for mongodb and um just click on connect so this is going to establish a connection with your local server your local mongodb your local mobile database server and i already have the connection here so i'm going to double click on it and it's going to open the window where i can see all my databases so i already have this case store set up as i already told you that i did not create it manually this was created when i ran my script for the first time by mongoose so you're gonna see how and i already have two collections the customer collection and the orders collection and i already have some documents so um i'm gonna delete them for demonstration purposes we're gonna do everything from scratch so i'm gonna delete the order as well okay so now you see my collections are empty and now we're gonna start writing some code so first of all as we decided let's insert some documents in the customers collection so for that you just go customer dot insert now there's two ways you can use the customer.create to just create like one document just just enter one document and uh also you can use the insert many method on the customer collection now using insert many as the name suggests i'm going to insert multiple documents at once so since i'm going to insert multiple documents at once i'm going to need an array and inside that array i will create two different objects and now inside these objects i'm gonna enter the fields that i have in the customer collection and the value of those fields so i have a name and this is the name that i want to enter and then i have an email field so similarly i'm gonna add the other object which will be the second document okay so this one's our two different documents and my customer collection and i'm just gonna print it so i'll say customers and i'm just gonna console.log it to see what was entered in my database okay and like all good programmers i'm also gonna catch any errors if i get them all right so let's run this code and see the magic okay so i have the result here don't worry about the deprecation warning here we're gonna ignore it and i added a console log which said customers added and these are the two customers that were added joy trippiani and chandler big okay perfect so the console log seems all right but now let's go to the database and see if these customers were actually inserted so i'm going gonna go here go to my customer table oh not the table the collection sorry yes i've been using the sql database a lot so yeah bad habit so i'm gonna go to the customer collection i'm gonna refresh it and voila you there you go you have both the customers appropriately added so each of these objects you see here each of these entries this is a document so each document has a unique id which is of type object id that i was trying to explain it before so this looks something like this like a longer hex string and these are the fields that i added for my customers collection similarly for the next document you're going to see all these fields okay so looks like everything worked let's go and perform some other queries okay now that we have two customers let's go and delete your customer so now to do that i'm gonna use the delete one method on the customer collection so on the customer model and i'm gonna return it so as you can see that these queries they return a promise so i'm using the dot then way of accessing these promise you can use async await or callbacks anything you want okay so i'm going to return the customer.delete1 i'm going to return the result from here and then i'm going to catch it here in another.then block so that i can change these promises very in a very clean way so it's easier to read so okay so now what do i want to delete i want to delete one of the documents from my customer collection so i'm going to pass any one of the field for the document so for example i'm going to pass the name here so do you understand what kind of a query this is this is like a delete from our query so like delete from the customer collection where you see the name equals to joey tribiani so that's what it's gonna do and now i returned the result here i'm gonna get the return result here and say deleted customer and i'm going to print it as usual so i'm going to print i'm going to console log the result okay so let's see what happens when i run the delete one query here and there you go okay so now since i run the script again it's going to add two more new customers called joy trivia and channel bang and then it's gonna delete one customer named joey tripiani so now you're going to still see two entries of chandra bing and one entry of joey tribiani so let's go and validate this from our database and i'm gonna hit refresh and there you go two entries for chandra bing but this is the newly created entry and here you go since we deleted one of the joey biani document we still have the other one so we successfully deleted a document using mongoose and also in the result that i printed you see that okay one and deleted count one so that means one document was successfully deleted okay next what do we want to do let's go and find all the customers from the customer table so that we don't have to go and check the customers and using mongodb compass we're going to see the list of the remaining customers here in our console so i'm gonna go do a customer dot find so this is like a select star from customer kind of a query so i'm gonna return the result again and cache the result in the next dot then block so i'll say remaining customers and then i'm going to console log it again so a good old copy paste so remaining i'm going to edit it to just say remaining customers and use this variable to print the customers that are remaining on our in our mongodb customer collection okay so let's go and run this all right so since i ran it again you're going to see so two more entries would have been added for georgetown so one of the entries would be deleted but we're still going to see i think three entries now yeah for chandler bing and one foreign but since i can understand this can be confusing for you i'm going to delete everything from my customer collection and rerun my script so that you see the result crystal here so my customer collection is empty now my orders collection should be empty as well and i'm gonna re-run the script so for a refresher we insert two different documents in our customer collection one for joy to granny the other for chana bang then we delete one of these document so we delete the joey tripliani document and we're gonna next we're gonna find all the remaining customers so all the remaining documents in our customer collection so this is what we have done so far i've emptied all my uh collections and my mongodb so let's see what will happen when i run this script okay so now the result that we have to expect is that we just want to see one document for chandler bing in our customer collection and i think this is what we see here so customers added to then we deleted joey tobiani and the remaining customer is transmitting all right and let's go validate this in our customer collection using mongodb compass and that there you go that's what we found so we just found one document for chandra bay perfect so let's go ahead and add an order for our existing customer so let's add an order for channel bin so this will be our insertion with the use of a foreign key and in order to do that i'm going to go here and first of all i want to save the customer id in a variable so because i'm going to use the customer id to perform the insertion in the order collection and how i can do it is i'm going to first fetch the customer id here i'm going to save it in this variable that i just created and i'm going to get the customer id from the remaining customers and since we saw that the remaining customers was an array and the customer that i'm interested in was at the zeroth index of this array so i'm gonna access the zeroth index of my remaining customer and then i'm gonna use dot underscore id field because that's how save the default id field in all the collections we already saw that okay so next i want to insert the order in the orders collection so since it's a single document i'm just going to use the dot create method on the orders collection and i'm going to pass an object it won't take an array because i'm not inserting multiple documents like before like i did here in the insert many uh when i use the insert mini method i'm just creating one single document so it will take an object and in this object i'm going to add the fields of that are present in my orders in my order collection so the first field is total the total purchase price which is 45 and the next field is customer underscore id so this customer id is the id of my existing customer which which i stored here in the customer capital i small d variable so i'm gonna use this value for my customer underscore id field of the orders collection all right so that's how we insert it not yet but we're gonna insert it when we run the code i'm just gonna return the result here so that i can catch the resultor in another dotted block and i'm gonna say order and now i'm gonna print this order that i will insert and the orders collection so and this order is associated or like this order is for the existing customers because it has the reference customer id so i'm gonna say um order here i'm gonna print the value of my order variable and let's see what happens okay from now on whenever i run my script i'm going to clean all the collections in my mango database so that it's easier so that it's easier for you to predict the correct outcome okay so everything is cleaned up let's go run the script and we see that two customers were added one of the customer was deleted the remaining customer was challenging and there was indeed an order that was inserted in the orders collection for chandler bing because i can see the customer id here matches the customer id of chandler bing so you see um it ends with nine fd one zero c here it ends with nine at d one zero c so there you go we successfully added an order for an existing customer who was channeling okay so everything looks good in the console.log let's go to the mongodb compass and see if our customers and order was correctly inserted in the database so we go to the customer's collection and you see that the customer channel bing was correctly added so we see one document only we don't see two different documents because we deleted the other one that was named bianni and now we go to the orders collection and we see that the order was indeed successfully added and we see all the fields the order total was 45 the customer id is correct we just validated it in the console.log statements okay next what we should do so we're going to find the order for this particular customer for our existing customer for chandler big so that we don't have to come to the mongodb compass and see if the order was correctly added right we're gonna see it in our console so let's find this order and in order to do that i'm gonna do the order dot find query so you saw that i've already used this query before when i wanted to find all the customers so but i did not pass any object or any parameter in my find method so this was like a general selector from the table name kind of a query but now i want a select star from where kind of a query so we i want a conditional select so that's why i'm going to do order.find but i'm also going to going to pass an object inside my find method to say that i want to find the document where my customer id equals this value because i want to find all the orders related to my existing customer with this customer id right so that's what i'm gonna do here and i will return the result here so i can catch it in my next dot then block and i'm gonna say um so because i've already used the order variable i'm gonna say selected order this time and the same thing again i'm gonna console log this variable to see all the orders placed by our existing customer with the current customer id let's go and run the script again so before that i'm gonna clean up all my collections i'm gonna run it again to see what happens all right so let's go take a look at the result we're gonna ignore the application warning so customer added two customers were added then one was deleted the remaining customer was changing the existing customers order was this and now you see that the order id is different because there was a new order that was placed and a new customer was created so i have a different customer id but it matches the customer underscore id field in my orders table so the order was correctly placed and the existing customer selected order so this was the select store from where so basically the order dot find query that i did that was the last query that i did and i have the correct document being returned but it's an array because i want to return all the documents related to the order of our existing customers so like all the orders that our existing customer placed so there can be multiple that's why this is an array and we just have one document we just placed one order for our existing customer so there you go the ids match and we were correctly able to select and return all the orders based by our existing customers so there you go we did a lot of stuff using mongoose for a refresher we inserted many documents we deleted one of the documents and similarly here you can use delete many as well to delete multiple documents and then we find we used the find method without any parameter and then we inserted a document in our orders collection using the foreign key concept so we also define a relationship between our customers table and orders table and we use that relationship to to perform this insertion so we use the parameterized find method as well and then we printed the result and then we catch any errors if we have any and we basically throw them also if you want to know how i know about all these options and all these methods it's really easy so you just go over the internet or google and you just type mongoose so you're gonna find the first link that's gonna pop on your screen i think that's yamangus.js so this is their api documentation all the methods and this is basically the official documentation all the methods all the operations that you can do on your database using mongoose are listed here you can just go through them all right so i'll see you in the studio for the outro so that's it for this video thank you so much for making it till the end of the video let me know how you like the video by clicking the thumbs up button and also leave a comment down below if you like the video and if you want me to cover any more orms any specific orm that you would like me to cover just let me know and i'll do that and also if you're not yet a subscriber subscribe to the channel what are you waiting for and you will be one of the first ones to receive any update from us and whenever we push a new video you're gonna get the notification so it's good for you and it's a great motivation for us as well to keep on pushing new content and improves improve ourselves and get better and better also if you want to get a scoop of our daily lives connect on our instagram channel the link will be down in the description as usual you can connect with us on linkedin as well on twitter and we also publish a newsletter every week so if you want you can go ahead and sign up for the newsletter on the immigrantprogrammers.com our website and we know your inbox is sacred so we won't spam you i promise so with that said i want to leave you with an end note i know it's so hot in some countries if you're like in the summer season right now so keep your fluids high drink a lot of water keep hydrated and that's it that's all thank you so much for watching and for supporting us bye have a great day
Info
Channel: Kritika & Pranav | Programmer Couple
Views: 3,267
Rating: undefined out of 5
Keywords: javascript, the immigrant programmers, programming, pranav, kritika, programming news, coding, coding news, tech updates, new releases, trending software, developers, web development tutorials, web development news, programmer reactions, coder girl, programmer girl, developer explains, learn programming, learn web development, learn coding, learn javascript, mongodb, mongoose, no sql odm, object data modeeling, mongoose js, nosql, mongoose orm, orm, mongo database
Id: b6vjbOk48_8
Channel Id: undefined
Length: 32min 53sec (1973 seconds)
Published: Fri Jul 16 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.