How to connect your NextJs app to MongoDB

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in this video we're going to look at using mongodb in your next JS applications hey friends welcome back to the channel if you're new here my name is Hamed I'm a full stack web developer and here on this channel we talk all about modern web dev topics like react and xjs let's go now you can self-host your database locally on your machine or you can use mongodb and their hosted solutions to create a free cluster and host your database online in the cloud and allow them to kind of manage that database for you so I've gone ahead and created a cluster for myself if you don't have an account you can just create an account here by signing in and then it will just onboard you to create a free cluster once you create a free cluster there you can you know create a database maybe a collection inside of a database this is not a mongodb tutorial and I guess you guys already know how to work with that I will have another video in the future where I will you know go through different concepts in mongodb but for now I'm assuming that you know mongodb and you can just go ahead and create a cluster and a database and a collection put some data inside of it where we would then fetch them in our next JS application and as a bonus you can just go ahead in your cluster click these three dots and load sample data set this is going to give you um if I go to this sample data set that I just imported it's going to give you some sample databases and collections we're going to use this sample and flicks in this video where we would have different movies here which is easier if if you wanted to build an application that uses different collections this is already some sample data for you to work for work with now to connect to our mflix database or this cluster that we just created if you just go back one step we will see this connect button and if you click on where exactly you want to connect to this database from for example from a mongodb shell from the mongodb compass which is a desktop application that allows you to kind of interact with your databases uh you might have seen this in my previous videos on this channel uh but for this for the purpose of this tutorial we're going to use a connect uh from your application you're going to copy this uh kind of connection string that you have assuming that you have already defined a user in the database access tab over here to kind of have a username and password that you can then plug in to this part over here uh that connects to this specific database and allows you to interact with different collections inside this database so let's go to our application and actually see how we can use mongodb in a nexjs application now we're going to create a new nexjs 13 application if you head to beta.txtjs.org this is the new documentation for the next.js 13. you can run npx create next app latest with this experimental flag app flag feature that allows you to kind of interact with the app directory and the new layout if you're not familiar with this I have a three-part video series on the channel explaining you know what's going on inside Nexus 13 the new features and the layouts and the server components and stuff I'll link it somewhere in the cart here but nevertheless let me just copy this and create a new next Js application okay and I'm going to go ahead and install this in the current directory and we're going to kind of follow along I'm not going to enable typescript for this project just for the purposes of com um you know connecting to mongodb we don't need typescript but you're more than welcome to go ahead and enable typescript in in your own project now once this is done we're going to then take a look at the different folders We have over here so as you can see in the new Nexus 13 if you pass that flag for the experimental app you'd see this app folder where hosts some of your page components and then you have this Pages directory where it can still host your API endpoints so to be able to work with mongodb we would have to go ahead and install mongodb mongodb oh sorry and PM not npx mongodb and the way that I usually like to do this is that I'll create a lib folder over here where you can put you know your utility uh or Library functions I'll create a directory and inside of it I'll create an index.js and this is where I can kind of connect to my mongodb and the way to do it is let me just copy the code here to speed up the process and I'm going to explain what exactly we're doing so I really started the dev server now inside of this mongodb file that I created inside of my lib folder if I close this for a second so we have more space if you're getting the mobile client from mongodb we are reading a mongodb URI so we have to set this to the connection string that we got from mongodb website once we created our cluster um if there is no URI well then it throws an error and if there is it it's just going to go ahead and create a new client and what he is here is basically sharing this client uh in a global variable that we can set here so therefore we are not recreating uh this connection uh every time that we want to query our database if there is a connection established we want to reuse that same connection so that we're not exhausting our connection pool that's taking care of that instead of just exporting this client.connect as order client promise which then on every request that runs this module creates a new kind of client and connection which is not ideal so this is the first step we would have to bring in our connection string in a DOT and file over here so I'm going to create this Dot and I'm going to pause the video bring my connection string back and we'll continue okay I copied my connection string in the dot end you should go ahead and do the same for your database to be able to kind of connect to your database now one thing that I like to add to my project is a JS config file that allows me to Define some options so let me just copy over this options you might be familiar with this if you have seen my videos before so this allows us to kind of access whatever it is in the lib folder with this kind of at sign in the in front of it instead of just going you know dot dot dot dot so something very unnecessary for this tutorial but that's just how I like to work so we have created our connection what's the next step well here let's say we want to fetch some movies so typically I would create another movies kind of file it which is going to contain my database access objects for working with my movies collection so let me just copy over the code that I have over here and explain what's going on over here so I'm going to import the client promise that we created in this step up top and then I'm going to kind of initialize our client by getting this client promise uh initialize our database by getting client.db these are mongodb way of working or accessing your database and then for movies I'm going to go db.collection and I'm going to pass the collection name which is movies in this case if I go ahead and show it to you here if I go browse collections in the sample inflix which I actually passed at the end of our connection string to directly connect to this database there's this movies collection which contains movies and information about the movies which we're trying to kind of fetch in our next year's app so and I'm once I run this module I'm I'm calling this init function to kind of establish this connection and get a handle for my database and for my movies collection and the way that mongodb bigquery's work is that you're going to use those handles to your collection and then drawn queries on it again this is not a mongodb tutorial I'm going to have a video explaining these different these different queries and the ways that you need to just generally work with mongodb in a separate video but in this video I'm assuming you know how to kind of query and work with mongodb and we're just implementing it in the next JS application so in this file I have defined one database access object or a function called get movies which looks to see if the movies handle already exists because I'm globally defining that movie's handle which is a kind of link to the collection if it's not available I'm initializing or calling this init function again to get that handled and then I'm going to run this query which calls the movies collection finds this is the way to find many resources or documents in mongodb I'm going to limit the response to 20. I'm going to map the underscore ID to the string version of underscore ID as you know underscore ID in mongodbs is of type object ID and returning object IDs from server to client because it's not serializable it throws an error so this is a workaround to just turn them into string so that they can be serialized when we are sending data from an API or from server to the browser and mongodb returns a cursor so I have to turn that into an array that's what this two array Radars and if everything goes well I'm returning this movie's kind of object back to whoever is calling this get movies function and if there is an error well I will just send an uh simple error message I don't want to send whatever error message that was returned to me because you don't want to expose the details of your system to the user or to the client side I'm just sending a generic cut error message over here okay so we have our connection to the database and we have our get movies function let's now create an endpoint API endpoint and fetch some movies to test this out so in the API I'm going to create a folder I'm going to call this movies and inside of it I'm going to create index.js okay now let me just again copy the code and explain what's going on here so I've defined a Handler that's the regular way of defining endpoints in next.js nothing crazy I'm expecting a get request for movies and I'm going to call this get movies function that we just defined in our mongodb database and I'm returning that uh as a Json to this API and if anything goes wrong I'm returning a 500 error with an error message and I'm only expecting a get request on this endpoint so therefore if I receive something else I'm going to respond with a 425 so let's go to localhost 3000 and see what's going on over here so we have the regular home page as you can see this is what comes uh stock with next JS app so I'm going to go to API and forward slash hello this is again what comes in with this hello JS which returns if you look at it this Json with the name John Doe so let me just make this a bit bigger okay now we're going to hit the movies endpoint which is supposed to give us uh movies as you can see uh we got 20 movies back from our mongodb database now to take this further why don't we go ahead and actually fetch this movies inside of our app directory in a server component and show them on our app to actually show that this kind of server components and fetching data on the service side with this mongodb connection also works in the in the app directory so let's go to the pages uh this is where our home page is living so inside of the app directory again if you're not familiar with the app directory please watch the video that I have on the channel you have a layout which is kind of like the underscore app and underscore document JC next year is 12 and then uh your page uh where it would have been like index.js in the next js12 it's going to be a page JX inside of an app so inside of this Pages directory I'm just going to actually delete everything that we have over here so what I'm going to do is I'm going to fetch some movies and the way that I'm going to do this is I'm going to define a function called Fetch movies inside of it I'm going to call this get movies um again the same get movies function we created to fetch movies from our database the same thing that we used on our API and then inside of my home page actually what I'm going to do is that so I'm going to call this function that gets the movies from the back end and I'm going to just map over these movies and for each one I'm just going to render their title so we deleted everything that was there added this function that fetches movies called Fetch movies inside of our page component and again this is the new convention these are server rendered or react server components you can turn them into a sync and fetch data directly in your page component so A New Concept and then we're just going to render movies and their titles so let me just save and see what happens over here yeah as you can see we got the titles of our movies here on our page which which means that we were able to not only fetch movies or work with the database connection that we had and database access objects we created for mongodb inside of our API routes here we were also able to fetch data on a react server component because by default all the components in the app directory are react server components so we were able to fetch movies there and basically show them over here that's a wrap for this video folks I'm going to have a more in-depth mongodb video in the future where we would walk through reading and writing and running different queries against mongodb but in this video we just wanted to incorporate mongodb into an xjs learning what is the correct way of connecting to the database without exhausting or connection pool or overall how to organize our project having different files and folders for our database access functions to kind of nicely connect and get the handles to different Collections and run Koreans against our database we also looked at actually fetching data in the new app directory which is running react server components by default and we're able to fetch some movies over here if you have any questions leave them in the comments for me I'm pretty responsive there and I'll see you in the next one bye
Info
Channel: Hamed Bahram
Views: 38,542
Rating: undefined out of 5
Keywords:
Id: mOvW3iheF14
Channel Id: undefined
Length: 17min 11sec (1031 seconds)
Published: Sun Dec 11 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.