Learn Objection.js - A NodeJS ORM with Knex Query Builder

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hola welcome back to the immigrant programmers channel my name is kritika and as you know a couple of weeks ago i started started an orm series so i cover some fantastic node.js sql based orange so far just to jog up your memory a little bit and if you haven't watched those videos just go and check them out so far i've created a video on bookshelf and sqlize so if you know if you wanna know more about those urms go check out the video the links will be down in the description below as usual and in today's video i'm gonna cover as you must have gotten a huge hint from my screen i'm gonna cover objection.js yes so this is another sql friendly node.js orm and the good thing about this is the syntax that objection.js has is really easy to use and understand it's pretty intuitive and also they have this excellent documentation so um i just wrote objection js documentation on google and uh i don't know even you you don't even have to mention documentation i think it's gonna be the first link that pops up on your screen so just go check it out and also they mention the benefits that you're going to have by using objection.js so let's go through them real quick so it gives an easy declarative way of defining models and relationship between them as i already told you the syntax is very intuitive and it's very easy to use very easy to understand and also yeah that's a good point so they have official built-in support for typescript so you can use it with javascript or typescribe whatever you want to do and also they have json schema validation so you can also validate your database fields your columns and the the data types you want to use for them and other stuff so we just let we're going to cover all of that in today's video so we'll see how we can do that now before that also if you go to the get started page you have the rest of the documentation here so you can go check it out at your own time all right so the first step would be to install our packages so first of all we want to use an objection so we're going to use we're going to obviously install objection but as you must have noticed in the documentation it's built on the next sql query builder if you don't know what that is i've covered it in my last video and my previous video which was on a bookshelf so i'm not going to go in details over it again um so what we're gonna we were gonna do was we're gonna install objection and next because we know that objection uses next all right so let's go to the code we're gonna install objection oops objection next and also since it's x sql based database you can also install any sql based package so you can either use it with mysql postgresql sqlite whatever my favorite database is mysql so i'm gonna install that and also mysql2 which is another package used by mysql so go ahead hit enter if you're coding with me right now i'm not gonna do it because i already have those packages because you see that i already have the okay very funny so yes go ahead hit enter so after you've installed all the packages and if you've seen my previous video videos on orm you know what the next step is any guesses yes it is to establish a connection with your database so let's go ahead i already have the file open and as always i already have defined the model structure i have all the boilerplate codes so that we don't waste time i know your time is really well valuable okay so first of all we require the objection uh library of course and we use the model class from objection library also we require next now in order to initialize my database in order to initialize the next object and make a connection with my database so what i do is what i'm going to have to do is i'm going to have to provide the info some information about my database so such as the client that i'm using which is mysql also the connection information about the database so the host where my database is located so my database as you can tell is located on my personal computer so that's why i've given the ip address of localhost you can also just type plain localhost as a string here and next you have to give the username of your database so of course replace here replace this information here with the username of your database and the password so this is my of course replace it with yours and the name of your database so the database is called kstar okay next what we do is this step is where we amalgamate next with objection.js so as i already told you they go hand in hand they use uh the objection.js library basically uses next so here we provide the next instance to the objection model so now this model this objection model it already has all the information about my database here and we're going to use it to create our models of course okay and now i just simply export my next instance so this is all just boilerplate code pretty i mean it's very straightforward if you have any questions you can ask them in the comments in the chat section i'm going to answer them as they come so meanwhile i'm going to move on to the next part which is defining the models now for the sake of this example as in all my previous examples that i've taken in the rest of my orm videos i take two database um so basically my database has two different tables so there's two different entities one is the customer table and the other is the orders table so what is the relationship between my customer table and the order table it's a has many relation because a customer can have many different orders so a customer table will be related with a has many relation from with the orders table with the order table okay so now we've understood the table structure we're going to define our very first table or the very first model as i should say um since we're using an urm which is this is going to be okay we have a comment here tran of says that this is my favorite word oh no okay he says which orm is your favorite sorry i read that wrong yeah sure tell us tell us which orm you use the most what's your favorite orm in the chat below okay so moving forward um [Music] moving forward where were we we were defining the customer model all right so first of all we have to again require the model class from objection library of course because this is what this is something that we're going to use in defining the models and now the models in objection js and with objection libraries library the models are defined as classes okay so therefore you see the class keyword here and the name of my model is customer because the name of the table is customer of course which extends the model class so this is a case of plain symbol inheritance and since you know javascript it doesn't uh no just doesn't support like multiple interesting inheritance so uh we just extend the model class we just inherit from the model class so each of my model is going to do the same all right so um next if when we have a class we have to define some constructors some functions some methods i should say because it's a class so my the first method that i define here would be a getter which is the name of my table and i return customers because that's what i would like to call my table that's the name of my table in the sql database okay so this is my customer table now these two options here these two methods here these are optional methods you don't necessarily have to create them so the thing is that um i like to have a created ad and an updated ad field in my sql tables so that's why i do this so this is how i create the created ad and updated ad fields using objection.js library so if you don't want to do that you can totally skip these uh methods right here all right let's get to the cool stuff so we're going to define the fields that we want to use in our customer table so the first field is the name field so that's what i did here i define a getter for the name field and the next field that i have is the email field and that's why i do here look at it for the email field and next what i do is so this is really cool so we saw in the documentation uh we have someone here with a comment that i don't understand loop back okay could you hi sandeep would you like to explain your comment because i didn't understand it all right so meanwhile he does that we're gonna move forward um so okay next we read about this in the documentation so this is the optional json validation the optional json schema that we did we can define in order to um validate the data that we get we're going to put and that we're going to insert in our database against the fields that we have so for example i can set a required field so for my customer table whenever i want to do some insertion i want to set the name field and the email field as the required field so if i do an insertion and i do not provide the values for any one of these field so um objection js is going to give me an error and i will be a validation error so that's how i can check that all my required val all my required column names columns have correct values now next i can define properties so properties are basically the columns that i'm gonna that i have my id column would be a type integer so if i try to add anything else except for an integer it's going to throw an error also i can understand after seeing that you might have a question that i never defined my id column here i never defined my id field but for a weird reason i'm using it here okay so the thing is that you don't really have to explicitly define the id if it's uh it's basically a default that objection knows and it's going to be auto incremented so if you want to change that if you want to change the default then you need to uh explicitly define the id otherwise it's good it's uh objection is going to take care of all of that so you don't have to worry about it all right so we move forward um name so my name is a type string so i can only use string values for my name field i set a minimum length and i also set a maximum length so my name has to be between 1 and 255 characters it cannot be below that so i cannot send like an empty string as the name or i cannot use more than 255 characters so that's another validation that i put here next is email created out so okay i think you get the idea i think you know now how you can use validation okay so i'm gonna move ahead and i'm gonna go to the relation mapping so as i already told you my customer table is related to the orders table and how are they related they have a has um many relation okay but i think by mistake i've used has one relation here that's not a problem we can we can use uh husband husbandy no but wait okay wait sorry i got confused so i've used the has one relation here because i'm defining the relation based on my order class so my order has to have one customer so like each order is associated with one single customer the same order cannot be associated with multiple customers right yeah all right oops that was a weird confusion okay now next we're gonna define the relation mapping and i'm gonna define it with my order class so this is my order object here this is basically the name that i've given uh to my mapping now the relation as i already described is has one the model class that i want to use is the order class so this name and this class here doesn't have to be the same this is just the class that you're defining the relationship with and this is the name of the relationship you could have used any other name here so don't get confused so pranav has another comment here one customer one customers can have multiple orders yes so one customer can have multiple multiple orders of course but one order can only be associated with one customer yeah i know it's a bit confusing but uh but i think i try to explain it the best in the best way possible so i hope there's no confusions now if you guys have still have some confusions ask questions okay okay meanwhile we're going to move forward um [Music] so yeah so the class is the order class so the model class is here now we define a join object so i'm going to define okay so i think frank got it says that's fair one-to-many relationship all right perfect so okay uh now the confusion is cured i'm gonna move ahead and we're gonna define our join object so what does it do is so it's gonna join the two tables but from the customers.id two orders dot customer id so this is my foreign key the customer underscore id field as my foreign key which will be present in the orders table but this foreign key will be associated to the primary key of my customers table which is the dot id so do you understand the the i'm sorry excuse me do you understand the relationship between uh the customer table and the order table it's pretty straightforward right from and two so basically my customer underscore id and my orders table will be related to the customer id in the customer table table so very straightforward awesome i'm gonna export my customer class now because i want to use it in my index.js file to do some queries to write some queries yes um awesome so we have defined our customer model and now this is clear why i explicitly required the order class here because i wanted to use it to define the relationship all right so uh next we're gonna define our order table the order model i should say all right so what we do is uh we again um require the model from objection model class from objection this stays the same this is my order class i'm going to extend from model the first getter that i set it sorry the first getter that i create will be the table name which is orders again i like to have a creator that updated that field again this is totally optional if you want to skip the step you can next i'm going to define the name names of my columns in the order table so this is the total column the total field so there's an order total which contains the total purchase price and i'm going to return my field total now the next thing is the customer id field so this is the foreign key as i explained in the previous uh minute i think um so this is the foreign key which is associated with the primary key of the customer table all right so i think that's all that's pretty much all the fields that we have for the orders table now um give me a second i'm very thirsty yes this reminds me it's summertime you should all take your fluids very seriously so drink a lot of water stay hydrated okay moving forward we can now also define the json schema which is the validation again it's the same thing that we did for the customer table uh right here so i did the same thing same exercise for the orders table as well i'm not gonna go through uh with it like one by one since i already did this for the customer table so i think this is pretty straightforward very obvious also if you have any questions again ask them on the chat and all this code will be so this code is already uploaded to github and i'm going to put a link to my github repository down in the description below because i know your time is really valuable so uh as always you're going to find the link down in the description below you can take reference to it if you don't understand something just go through it ask us questions in the comment section even after the live stream ends we always reply okay perfect so we have defined so far we have defined both our models our order model our customer model what is next yes we're going to write some queries we're going to query our database so for that we go to the index.js file now i've already set a flow here for you we'll go through it first um as usual as a ritual i'm going to require both my models i'm going to require a next instance so uh as you must have seen i'm going to use the async await structure here because like objection.js it works with promises i'm going to use the async await structure you can use promises.then or like callbacks whatever you want to you are comfortable with so i'm gonna execute all my queries inside the main uh function inside the main method no i should call it function here yeah inside my main function so um after i am done executing my queries i would like to destroy the next instance so there's no leakage and my database is correctly destroyed after i use it sorry so that's what i pretty much do here if there's no error i just destroy my next instance if there's an error i catch it i console uh log it um i just log the error and then i destroy my next instance that's it that's all all right next i have the flow already decided what we're gonna do so we're gonna see first of all we're gonna delete all the persons from the database and all the orders from the database uh sorry this should be customers okay so it's more representative customers so since we have a customer table and an order table we're gonna first uh delete all the customers and orders from the database because i ha already have something um is it too small for you can you see the database i'm not sure if i can enlarge it yeah i try to but i can't so i hope you guys can see it so there you go there's already some data inside both my tables customers and orders so we're gonna start by deleting it okay so how we're gonna do that we're gonna do that using um objection objection.js so it's pretty straightforward very easy okay so we're going to do customer.query.delete and order.query.delete so these are the delete function very intuitive intuitive as i already told you and the delete function deletes any uh any pre-existing data from your tables so let's go ahead and execute that okay since i did not put anything in in the logs so i didn't put any console log so you see uh nothing printed here let's go ahead and let's see if our database uh if our if our tables have been cleaned up so there you go it's all cleaned up so we have successfully deleted data from our database okay france says it's fine we trust you that data was added okay yeah i know okay perfect so now you should also trust me but like i have proof as well we deleted the all the data all the pre-existing data in our databases so okay let's go back to the code we have already seen how we can delete stuff now let's see how we can insert uh some stuff into our database so first of all i would like to insert something in my um customer table so there you go what i do is i'm i want to insert so the um the syntax is very straightforward once again you just go customer.query.insert and that's how you insert some stuff so i'm going to insert my first customer which is rachel green yes another friend's reference great fan great fan by the way with any of you catch the french reunion yesterday yes no okay i was amazing by the way all right moving forward i will not digress much okay so moving forward um uh we inserted our first customer we added the name rachel green we added the email rgb gmail.com and uh let's see um first of all this time i'm gonna add a console log as well so i want to print my customer object here okay so let's see what happens when i run this query and then i'm gonna show you another great concept as well so i'm gonna run this sorry alrighty so this is my result right here so i have my customer i have the name the id which is 45 it was auto uh generated and my creator that field because i just added it for the first time i didn't update an existing entry so i i just you you're just gonna see create it i've not updated that all right perfect so my customer has been added successfully and i know you guys trust me and you trust that it has been added to the database as well but we're gonna check we're gonna go check okay i'm gonna refresh everything go check the customer table i voila you have the first customer correctly added in the database as well i know it's too small for you to see but uh just see the selection if it's possible for you i don't know um [Music] okay but then again you guys trust me okay so uh we have already seen it in the console lock statement that our customer was correctly added and it was returned and i stored it into a variable and i printed the value of that variable so there you go now don't you want to check if the validation that we put for the customer table works so the json schema we put here right you want to check if it works let's check it so um we made the name field required so if i just go ahead and check change the name of my field so i just uh type in some gibberish uh to change the name of the field from something else from name and now let's see if the validation works and if objection.js throws me an error okay let's go ahead and run this and there you go model validation status code 400 and let's see what the error is name is a required property and there you go because i made name a required property and here when i do the insertion validation doesn't doesn't find the name property so since it can find the name property it to an error all right so the validation really it does work okay all right so um that's a good thing that's a good start so we deleted our existing entries we already added a customer we also printed the customer next what you want to do next we want to read from the database okay we could do that but i guess we have already uh logged the customer but okay we could do a read query as well what the hell all right um [Music] so now this is a read query if you don't so the customer dot query so this basically returns all the entries in my customer table and i'm gonna also print the um all the entries the response that this query returns okay so i call it customer read in order to differentiate it from my customer variable here so okay let's go ahead and give it a try all right oh say okay i don't understand is this the uh is this the response from the upper query or this query um it still looks like the old response oh wait okay i didn't save uh the file i think before running it oh gosh bad habits okay i'm gonna run it once again and this time i think i'm gonna pro uh i'm gonna give it a little marker here oh yeah i will just say the name of the variable that i'm needing okay there you go just to differentiate between both the control lock statement okay okay there you go it works fine it was just my stupid idea i forgot to save the file if you if you checked out my bookshelf video i did this a lot a lot in the previous live stream and it was so stupid half of the time i was running why the code doesn't work and it was all that i forgot to say okay i won't do it again i promise i will take care um so the first uh first console log returns this this is the entire customer object right here as you can see and the second console log was the customer read so yes this is the this is basically all the entries present in my customer table which is the result of this query right here so this is equivalent to doing a select store from customer that's it that's all you get all the entries present in the customer table that's why you can see this is an array here but you just see like one entry because we've just added one customer so far yeah logic okay so this was an object this is an array so yes this is like a select store from customer cool so so far we have inserted um inserted some data we've read data we have also deleted data what's next the next thing is to add an order for this customer okay we can do that we can do that we can add an order for this customer and there you go that's how we do it so what do we do here we do a related query because if we want to add a simple order which is not related to any customer we can do that we can do that simply by using the insert query but here this query is slightly different because here we also we want to insert an order but we will also want to trigger the relationship of the order table with the customer table so we also need this customer id because you know we also have to fill the value of the foreign key present in the order table the customer underscore id form key right which is associated with the primary key in the customer table right okay so now the syntax says we do a related query again very easy to understand okay so first of all i see that this file is not saved i'm gonna save it first all right so related query on which table do you want to relate this query to i'm going to relate it to order table so we're going to relate this to order and uh for which field for the customer dot id field and here you don't say customer underscore sorry the customer underscore id field yeah you don't say that because we're doing the query with respect to the customer table so in the customer table you have customer underscore id and if you don't remember where this customer instance came from it's from here i saved the uh the result of the insertion in um in a variable and i call it customer so i can access the id field of the customer okay so because like as you can see here this customer object has an id has email name so i can access any fields by just like normal object uh manipulation so just dot on the name of the property okay so um where was i so yeah we're gonna use the id of the customer so customer.id because we're doing the query with respect to the customer table okay and then what do we want to do we want to insert an order for this customer but since we're doing this query on the order table we're going to use the fields of the order table so um i'm going to say the total purchase price is going to be 90 awesome so now we have our order ready to be inserted let's see what happens when i run this code we're gonna see many control logs here now but where we have already seen like both of these were interested in this one okay so we have the customer here we read the we basically printed all the entries present in the customer table and now we added we successfully added an order for this customer for the purchase price of 90 the customer id is correctly saved which is 48 and if you see the id here the id for our current customer is 48 as well so this order really belongs to our current customer okay and the rest you know this is the id field of the order table okay the rest is uh all right the created out field so when the order was added when it was created again you're not going to see the updated art field because we inserted this order for the first time okay so we added an order for the customer now what do we want to do next we're going to do a select query on all the orders so we're going to get all the orders for this customer so this is a fun query i tried to cover as much uh possible as much as possible so like different uh methods that you can do with query so with this like query method so let's see what we can do so we want to get the total orders the order total for the current customer and how we're going to do it so first of all order dot query um we should have you should have memorized this by now so or a dot query then we can do a select yes we can do a select of a particular field so i just wanted to select the total field that's it that's all i don't want the rest of the fields no id no created and no customer id just want to select the total view all right so there's there's a selection of specific fields inside a table then i can use a where clause in my where clause i want to select the orders of only our current customer so i'm going to use the customer underscore id field present in the order table but because again we're going to do the query we're going to do the selection from the orders table audit table so uh the customer underscore id where it equals the customer dot id because again i have the id of my current customer so where this clause is satisfied and i can also do an order by total okay so i can so log this order total now what i want to do is okay let's keep all of the console logs uh for a reference for now okay and i'm gonna run this but i wanna put a marker here so this is my final order so order total so this will contain all the entries all the results that satisfy so all the results that of satisfy these conditions so it's going to written all of them so it's going to be an array okay so let's go ahead run this and see what happens so there you go it is an array and since we just have one order in our order table it just returned this one of course like for this customer we just had one order and even overall we didn't put any other orders so there you go it correctly returned the order for this customer so this is equivalent to a select total from order where customer id equals to customer dot id so like a select from where query and then you order by you just add like another keyword so yes we have covered a lot of stuff we have deleted we have inserted data we have done uh insertion related to um we have done an in a related insertion with foreign key and staff and also we have done a select from where query and use order by as well so yes i guess i let me check my agenda that i wanted to cover today and yes i've covered everything related to this library so again this is a wonderful library i really use it a lot of time i think i like it even more than i think sqlize if i dare to say that because it's really simple this library is really simple easy to understand and also um do we check the database uh for the for our our tables the last time the order table and the customer table okay we did okay and everything is correctly added perfect so that's out of the way yeah if you go to npm and you if you check the weekly downloads for this library i mean it's pretty i mean this is quite commendable and almost 80 000 downloads per week so it's quite commendable and uh but i think honestly speaking i i feel that uh the this library is so awesome this number looks pretty small to me because like it has so many good features to offer but maybe people prefer to use equalize more because like they're more famous and yeah and like the other libraries like type typescript worm and stuff typewrm so yeah um but you can give it a try you can you can just uh go check out the official documentation i already showed you also a link to it will be provided down in the description below and just go get started get um get some get some hands-on practice okay so uh thank you so much for making it till the end of the video with me it was an amazing live stream uh i really enjoyed it with all your questions and comments and everything so thank you and um just on a last note i would like to mention that we write a a weekly newsletter so go to our website the immigrantprogrammers.com here a link to this as well would be um you will see the link down in the description and just go here and sign up for our weekly newsletter so if you if you're like a visual learner you have our videos that you can go through if you're a reader or a writer if you learn more by reading stuff so these are our weekly newsletter we also write articles about what's happening in the web dev industry and stuff so oh hi sandeep uh he says thank you this was really helpful please share the github thank you so much sandeep for your comment sure so as always the link to the github repository will be down in the description so as soon as i end this live stream i'm gonna do that and um yeah that's it so subscribe to the channel if you haven't done that already if you find our content useful just share it with people like and comment it's a really we really appreciate uh when you do that it's really motivating so yeah without taking much of your time thank you so much have a good uh enjoy the rest of your day it's summers here at least in canada and i think in the rest of the part of the world maybe it's if it's summers keep uh check on your fluids drink a lot of water thank you so much bye take care you
Info
Channel: Kritika & Pranav | Programmer Couple
Views: 9,721
Rating: undefined out of 5
Keywords:
Id: lPlgRp6-CqU
Channel Id: undefined
Length: 40min 38sec (2438 seconds)
Published: Sat May 29 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.