How to use Mongoose with Next js 14 +?

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
okay let's be real wrestling with connecting your awesome nextjs app to a database like mongodb can be a total pain but if you are ready to build those super Dynamic web apps well hold on to your keyboards because we are about to make hi everyone I am Aya zafur and I'm all about helping developers like you get things done with the power combo of and nextjs I have seen firsthand how this combo can speed up development and make managing your apps data a breeze all right so why are we even bothering with and nextjs well here is the deal first one is structured data takes your mongodb database and gives it a backbone it lets you define clear rules and relationships for your data so it's not just a pile of random stuff floating around next is developer friendly makes working with your database feeli way more intuitive it's like having a translator between your JavaScript code and mongodb next one is full stack power next he has rocks for building the snappy front end of web apps and mongos lets you handle all that data on the back end it's a perfect team next one is maintainability code that's well structured and understandable is code you can actually come back to and update in the future without getting a headache helps with that picture this you are building an online store you need to keep track of products prices inventory maybe even customer reviews and orders or let's say you have got a super cool blog idea you will have articles author profiles maybe comments trying to manage all this without and nextjs that's a recipe for chos this combo makes it organized and dare I say enjoyable all right time for the foundation we will whip up a fresh nextjs project ready to work with our database let's assume you have nodejs setup on your machine if not there are tons of guides out there to get that done quickly or you can check videos about that on my YouTube channel where I have taught how to install and manage the versions of your nodejs now fire up your favorite terminal and now let's use the magic of npx create next app CLI and we will call this project something like next demo you can call this project anything like next demo so let me open the terminal and this is how you will type the command npx space create D next- app at latest and press enter or you can simply space and type the name of the project in the same line and press enter this command sets up the nextjs project and importantly gives us the site app directory where the new routing and data fetching magic happens now let's get the tools we need our project is built already I already have built my project and it is open my vs code and it is currently running here in the browser so once your project is built now let's get the tools we need in the terminal let's install the mongus so for that open the terminal in your in the root directory of your project and type the command npm install press enter And since we are big fans of typescript so let's grab the definition types too so for that once this is installed for that I will run the command npm install D- save-dev at type SL mongos press enter okay the the types have been installed now we need to wait for for the to be installed okay have been installed as well you can see that these are have been added in the package.json file as well okay earlier types were not installed so I ran the command again and now I can see that the types for the mongos have been installed okay great if you don't have one then set up a free mongodb Atlas account this gives us a hosted database to play with so let me create the atlas account along with you so let's open the so let's click on this link and let's click on the start free and from here I will you may manually type the information or you can use your Google account to sign up so I'm using my Google account to sign up all right my account has been created with the help of the Google account so I have accepted the terms and clicked on the submit button all right uh it is showing me a welcome screen use your account to deploy the cloud database with mongod Atlas welcome to Atlas let's build something great help us tailor your experience by taking a minute to answer the questions below okay let's see what is that getting to know what is your primary goal let's see I want to build a new project or evaluate and I'm new to mongodb getting to know your project uh we are using I guess nodejs here and what kind of data will your project use not sure for now and will your application include any of the following architectural model uh I don't know click on the Finish okay now it is asking you to deploy your database use a template below to set up Advanced configuration options you can also edit these configuration options once the cluster is created now here are different options this is these two are paid but this one is free uh this one has the 2 GB of RAM and 10 GB of storage but free one has the Shi shared RAM and 512 MB of storage so for now that I think this is sufficient for us here you can select which provider you want to use so let's keep the AWS far now and let's keep the region that was selected by default and here you can give any name to your cluster and let's hit the create button and wait for it if it shows you the capture to verify if you are human then let's fill that out and I think let's try it hit the submit Buton okay all right it is provisioning our cluster so security quick start to access data stored in Atlas you will need to create users and setup network security controls all right how would you like to authenticate your connection your first user will have permission to read and write any data in your project all right so the cluster has been provisioned as it is saying now it is saying asking to create database using username password user will be given a record uh given the read and write to any database privilege by default you can update these permissions or create additional users later ensure these credentials are different to your mongodb Cloud username and password all right it has suggested uh an autogenerated password so I think it is fine and copy it and let's hit the submit button to create the user now it is asking where would you like to connect from enable access from any networks that need to read and write data to your cluster one option is my local environment second one is cloud environment in the local environment use this to add Network IP address to the IP access list this can be modified at any time next one is cloud environment use this configuration network access between Atlas and your Cloud are on this specifically set up the IP access list Network paing and private endpoints okay set your network security with any of the following options okay I think let's keep it for now and here we will add my current IP address so okay saying that your IP address has already been added that's great and as this is my computer I address but in real world project when you deply your application to a live server then your server server will have its own IP address so you may want to get the IP address of your server and you will put it there and give it a description and you will add it and it will Whit list that IP address once done click on the finish and close Okay close it all right I think our cluster is ready and ready to be used once your cluster is ready then we need to click on the connect to choose the connection option so let's find out the connect button click on that and from here I think we need to choose this option drivers access your Atlas data using mongodb's native drivers like nodejs so let's do that and here you have to specify the version and then add your connection string to your application code okay so I have already copied and uh copied my password so let me put my password here for now and I will copy this connection string and let me paste it here and now I will cut my password and paste it here because this is a placeholder for the password you have to put your password by yourself okay now this connection string can be used to connect your database so let me cut it from here we never want to paste that connection string with your password directly into the code so inside our project let's create the environment file that would be env. looc press enter and here I will create a variable like DB URI and paste our connection string so that's the setup ready to make actually connect to our database okay now it's time to make nextjs and mongodb actually talk to each other for this we will create a dedicated connection file so in your project let's create a folder called lib this is common place to keep these helper functions so let's create a li folder and let me collapse this node modules so in the LI folder we need to have DB connect dots okay it has created the LI folder automatically and now we have the file now let's add some code here in this file so import mongus from mongos and now const connection is equal to actually we need to give it a type is connected and we have initialized it with an empty object now I will create an Asic function DB connect and here I will check if connection is connected so after that I will add const DB is equal to await mongos do connect and here we will access our environment variable that we created earlier uh after that line of code I will add connection do is connected so we are basically updating this property with the ready State and add at the end we will finally export this connection okay so let me quickly uh explain so here we are importing the we need to library to do the heavy lifting and then uh this connection object uh might seem weird but it's key to efficiency it lets us store if we already if we are already connected the DB connect function uh is our main function for establishing the connection so if connected then we will return if if we already have a good connection no need to redo everything and then we have the doc connect this is where the magic happens we tell to connect using the connection string from our env. looc file and then we are updating the connection status uh so we know if we are connected or not so why all that first nextjs apps especially with the app directory can execute code on both the server and within the browser components we don't want to create tons of database connections so it's wasteful this pattern makes sure we reuse a single connection for the whole app so ready for the next step defining our data models all right it's time to give our data data some structure models are like blueprints for what we store in our database let's build a simple model for a product so think of things you might have in an online store name price description and name obviously every every product needs a name this will be a string and then price we have to know how much it costs we will store this as a number then about description this is a place to give more details about our amazing product so let's make this another string we love typescript so let's define an interface and then create a models folder in your project and add a file named product. TS so let's do that here in the app directory I'm going to do that model SL product dots and now I'm going to create the and Export the interface that I was talking about I product extends document okay we need to import this document from mongus and now I will add the name String phone price and description and then I need to create an constant a constant product schema and we will initialize the actually let me give it the type schema that we created earlier now give it a type schema and that should be imported from the like that and now we will initialize new let me import the so here add like that dot and schema okay we have initialized it and we will pass it an object and there we will pass different things like Fields name and then we will have type type string and required true and then we will have the price and at the end we need description and this is not required so I will just get rid of that all right after that let's create another constant product is equal to mongos do models model dot actually here we need to pass the interface product and then I will call it and here I will pass the name of our document and here I will pass the schema okay now at the end I will simply export this model in this way all right so let's quickly talk about this code so our i product interface tells typescript what a valid prod product should look like the document bit adds mongodb specific goodies and then we have schema this is like the core blueprint it matches our interface notice the required bits these are the basic validations we finally create the product model here this is what we will use to interact with our database lets you get fancy here so required fields we have saw that already data types make sure prices are numbers not text and about custom validators you can write functions for more complex rules so feeling confident right let's put these models to work inside the nextjs all right now we can actually use this stuff to build our app so let's get some products onto the screen now that we have our model set up it's time to see them in action with our next GS app this part is exciting because it's where our app starts interacting interacting with our data database to fetch and manipulate the data so let's dive in first off let's create an API route that allows us to fetch our product data in your project navigate to the app directory under the app folder create a new folder called API and within the API let's create another folder name called products and inside the products let's create a file like route. DS and here I will export default async function and we will name it the get method so this is important you have to give it get post or delete or patch name so once that is done I will use a wait DB connect make sure to import the DB connect from the library that we created earlier and now after that get the products and save them in the products variable await products. find and then actually we have to import that schema like this and now response and now we are sending the status okay so you will use the next response. Json and pass the products you can further wrap it in the try catch block to capture the possible errors so you can pass that error message in this way and here I will add the any for now all right so so let me quickly explain so here we are ensuring the uh that our database is connected before handling request now let's create a page in our app directory with the name products slash page. TSX and here I will export default function and give it any name page and within that we will first create a function const and fetch products and now we will fetch the products in this way so we are accessing our AP route that we created earlier from this path and we are getting the adjacent and now I will return this okay now I will create a use state products set products and make make sure to import the the use State okay and now I will use the use effect make sure to import that function as well and with that I will pass the call back function and this should be called only once first time when the component is mounted and here I will use this fetch products function we call it and the promise we use a DOT then function and when we got the products we set it in the product State and once that is done I will return div and within that I will use H1 tag products and after that I will use products. map and let's return a div with the product ID and product name and for now let's type any here to get rid of these errors okay now let's quickly test it so here I will go to the products press enter and I got some errors you're importing the component that needs use effect okay so to fix that problem either you can convert it into the client component like this use client so in this way this has converted into the client component and right now we don't have any product so it will not show any but another important thing is that if you don't want to to convert it into the client component you want to keep it at a server component then no need to use the states we can just get rid of all of these just create a property uh cost products is equal to fetch products and actually here you can add async to use the aate here okay and now it is server component and it will it should still work okay to fix the that error you have to copy the base URL and paste it here so now if you reload it it will still not work because our API has some uh problem so this is our get method API and it is saying that cannot override product model once compiled so I think the model was created and it is trying to recreate it so for to fix that problem go to the product model and here we have to check that if mongos do model dot product then use it otherwise then create a new one okay with that hopefully this is isue should be fixed let me restart it okay now reload it okay we are getting error 405 and in the console I can see detected default export in this export are named for each HTTP Method All right so let's see what's wrong here so we don't need to set the default just export in this okay and now reload it okay now we have different kind of problem error the UR parameter to open Ur must be a string got undefined okay so there is some problem here it is saying that this is not defined so let's see let's go to the env. local mongodb maybe the uh name is wrong so yes the environment variable name was wrong now if we try again it should hopefully work fine so now so it is saying that no response is returned from the route Handler okay so make sure to return the response like that otherwise you will have problem like this okay now let's try it again reload it and this time you can see we are getting an empty array and this is working perfectly fine but right now we don't have data that's why we have empty array so let's create some data I will go to the database here in the mongodb and click on the database and here here okay in the database you will find the cluster okay from this cluster click on the browse collections so here it you can find that our products has been created and now I will add some data into it so click on insert document and here let's add some data like let me move it here so here I will add the data like name product price this description this okay let's copy it back and paste it here all right now let's insert it okay we have inserted a document now let's reload it and we should see that product here let me add few more products so I will insert document and here let's copy paste it and this time I will add different price different product name and different product description actually we have to be very careful because the ID should be unique every time so let me copy the this part and cancel it and click on the insert document and I will only paste the additional things here we need to add the semic uh comma and click on the insert all right now we have two documents if you reload it you will find the two documents okay now let's run it here reload it all right now you can see that our products are being loaded these are the prices and these are the titles and and the descriptions and there you have it we have covered how to set up model connect it to nextjs application and display data using server components this setup not only allows for efficient data management but also leverages the full power of nextjs server and client capabilities remember this is just beginning there is so much more you can do with nextjs and from implementing crud operations to adding authentication and Beyond so stay curious keep experimenting keep experimenting and don't hesitate to dive deeper into the documentation and Community Resources for more insights and best practices you have officially integrated mongos in your next GS project think about it you can fetch products display them and will cover creation that's a massive step towards building a full-fledged web application if that help you out do me a solid smash that subscribe button and hit the Bell so you don't miss the future tutorials where we keep experimenting on this here is my challenge to you what are you excited to build with this new found knowledge a Blog an e store something totally different drop these ideas in the comments and let's get our conversation going remember ACH is all about making web development accessible and fun so keep building awesome things
Info
Channel: AyyazTech
Views: 6,879
Rating: undefined out of 5
Keywords: API routes, Authentication, CRUD operations, Data fetching, Data models, Database integration, Frontend development, Fullfledged web application, MongoDB, Nextjs, Nextjs project, Server components, Web development
Id: bMHs2pHkbsM
Channel Id: undefined
Length: 26min 20sec (1580 seconds)
Published: Sat Feb 24 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.