How to use Mongoose with Next JS 13 for MongoDB

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
it's time to go today we are going to learn how to connect an SDS 13 application with the app directory to a mongodb database we are going to use our portfolio app our assistant portfolio app that we'll be working on to connect a to replace our local Json file data for a mongodb database which is a lot more secure scalable Dynamic and responsive if you are new to this video or to my channel don't worry you don't need to have a work in the assisting portfolio app you can just go to GitHub I leave the disk and the link in the description box below clone the project and take it from there okay you don't need to have the knowledge of what we've been doing before today we are going to learn a lot but we'll keep it short simple and fun there might be some surprise along the way not sure let's see let's get started first we need to create a mongodb account I already created a mongodb account when I Was preparing this project so but I screen record what I was doing and so I'm just gonna show you first you just go to the website mongodb and then if you have an account sign in if you don't try free you click there and my connection was quite slow at this point so hold on and this will take you to the sign up screen you just put here all of your details your email and your password and once you're done you click on create your Atlas account okay this will take you to a screen where they will tell you that you need to verify your email you go to your email you verify it you click in the link and then it will say that the email is successfully verified I will take you into this screen where you need to select your goal if you're learning mongodb or explore what I can build or so on I selected learn mongodb then here I just said I'm just exploring and my preferred languages JavaScript um cool and now it comes to deploying our database you choose from these three tiers uh of course free because we are only learning and include this option to just leave us as it is the provider and the video and the name here you can call it whatever you want I'm going to call it portfolio app and you can also create tags but I just left it as empty um you do this then you will take you to the screen where you can create your user so you can connect to your database and this user is what we are going to use in our uh what we are going to put in our M file we'll go over all of this and you can Wireless your IP so here I'm adding my current iPad today to the Y list and once I'm done I just finish and close I click that button and my database is created and it's deploying or is deployed I think this is all you need to do for now and just one more thing here if you click on connect it's going to show you a different way so how you can connect your application so for example by a driver of I Compass a shell a mongodb for vs code or Atlas SQL and if you want you can use Compass you can install this and I haven't done any of this I just use the URL that the connection string that you have down below but you can download it so you say like this part that I'm highlighting this is the string that we are going to use to connect to mongodb as you can see it has my username my password the cluster name and the the rest of the mongodb URL okay so that is and something that we need but I'm not going to install absolutely anything else I'm just gonna wear with the cloud first um as I said go to the GitHub link that I left in the description box below and a clone from this Branch videos three final unit test this is where we are going to take it from by the end of this tutorial I am going to push everything to this Branch video for final mongodb emails I might change this name to messages actually um messages so I might just remove this last part actually let's do this now rename it's as simple as this to rename a branch okay let's start with the tutorial now let's start to code let me put myself here okay first thing we are going to do it's uh run the project so yarn on npm whatever you use run that and we are getting this error they saying that we are not defining react in the lodge out so let's just go to the logout and here I'm just going to import react from react cool now our app is working and okay so first we are going to um go to our API API root and I'm going to create a new root file so first I'm going to rename this one and now root dot TX and basically we are going to completely replace the connection we have here and this connection we are connecting our API to our local the Json data and we are going to create a new connection to mongodb so all of this uh we probably don't need much of this to be honest okay so now that we have this new file and before getting into any other details I'm going to install a library called mongoose yarn at mongoose so this library that we just installed Mongoose it's um a library that is going to allow us to connect with the database with mongodb you can use other libraries or you could even use the mongodb one this one and but what I like about mongoose is that it's a high level tool built on top of mongodb driver this provides us a abstraction layer for interacting with the database with the mongodb database and with with Mongoose you can't find your documents using a schemas and we look into that and provides set to high level methods to query and manipulate the data it also provides some features like validation or middlewares and it really allows you to define a run complex queries quite easily okay so here now in Roots in here this one we are going to first let's import react from react oops okay and I'm going to just copy what I have here this we are going to sport on a sink post function just like this one but we also need the response not only the request so response next yes please what next response I'm going to change this to rack so it's the same okay let me make this smaller and uh here I'm going to import to Mongoose so um from on this and the first thing I'm going to declare is our URL our mango Yuri mango Divi Yuri and this mongodb Yuri is what I was showing you earlier this URL here I'm gonna copy this come here and paste it and just gonna replace this the username time to code password and the cluster portfolio app for um I'm going to store all of this in um environment variable so to do that just gonna copy this delete it and Open brackets with dollar symbol I'm gonna pass here the variable so process.m sorry let me just replace this for an equal process.m dot user um let's say username and I'm going to do the same four passwords so password and portfolio app this will be cluster okay so this are environment variables you could just leave the URL as it was all here but if you want to have different users depending on the environment where you're working on depending if it's development or production this is a good way of doing it now we need to create a file that is dot call Dot and and here in this file is word we need to specify our variables so username and you put here your mongod username and so on okay we save this and there is something else that we need to add to the nearest DS configuration if we want to work with mongoose so otherwise your app is going to erase so go to nest.config and here let's search for Server components external packages and here we um with the final array and within this we just need to pass mongoose okay save this and let's come here okay so this is our uh URL now we need to connect with a mongodb so I'm just gonna Define here a variable whole client and I'm gonna have a try catch block just to um to cut any error that we might have if if our connection with the database fails so in client I'm gonna weigh this because this is a promise and I'm just gonna say Mongoose dot connect I just pass here the DV here I'm gonna look um something here database connected okay and in the cat I'm going to also lock on camera so uh there was an era connecting to the database and now I lock the error okay save okay we Define the URL and then we connect to the database using Mongoose okay and we also have two console log just so we know if it's connected or if it was an error here a let's just save this first let's come to the page clicking send okay I need to fill in something okay let's see um we get some errors client server but okay we get some arrows here that's fine but the database is connected it's because we are not really returning anything but we can see that the connection with the database is working okay okay let's um get the data so this is in the we're gonna do it in the same way as we did it in the previous video like this I wait for the request Jason let's just do it again await Rec Json and now we are going to the structure our data so name email company message equal later okay and here we are going to have a need for statement we are just going to add some validation to it so let's just say if there is no name or there is no company or there is no message or um the message the email or there is not email okay and the email doesn't include oops doesn't include at um or the message dot trim is equal to empty strings um or actually the name dot trim is equal to empty strings let me just see where I have an error here okay if all of this is a full it all of this is true um yes sorry so if all of this is true then we want to throw an error right so I I go through it in a second so nestresponse dot Json and then here we open a curly brackets and we pass the messes and this is gonna be invalid input fill all the films and we can also pass a status quo so status and this is going to be a fortitude okay so what we are doing here is and we want we we're adding some validation so I think we have a few validations in the front but to make a really secure application your validation actually should come from the back because the front the client any user can actually interact with it um but they cannot interact with the packet right so here we are checking that if we don't have a name or we don't have a company or a message or a mail or the email doesn't include an ad or the message once that we trim it is equal to uh empty empty strings and the same with the name then if all of the is some of this condition is true and then we throw an error okay this is just a bit of validation just a bonus that we are adding in this tutorial and now and and we return it okay so you're gonna we're at this and now we want to return and now I'm gonna create a new variable called new data because I want to get the data that we have and add one more um fill which is date so new date like this and before I continue here I want to create a ice cream so if you are familiar with a graphql you might know what I'm talking you you might it might be might be easier for you to understand what we are just about to do but either way it's really easy and straightforward I'm gonna come to my root file root of the project and create a folder called models or model models yeah and here I'm just gonna create a model called messes.js here is where I'm going to Define my schema so the schema is a document where you define all your all the fields that you're gonna have and the types of them a let's import Mongoose so cons Mongoose equal require goose and now we can Define the schema so messes a schema this is equal new Mongoose Dot escema we all Open brackets and curly brackets and here is where we Define all our Fields so name and the type of this field is string then a email and the type is string then company and I think I removed one of the brackets company and this is also a string a next message also string and then we can add date and this is a type date and now we export this so module dot Sports equal mongoose dot module and then message messages schema okay this is the way that we can export it and there is something else that we can do here so um if we don't want to our code to compile this model every single time we run it what we can do is at here Monger Dot models. message or so what we are doing what we are supporting is magusto tomato messes or mongoose.model we are compiling this project so basically what this code will do is it will use the compile module if it's if it assists but if it doesn't exist it will compile this module cool now we can import this in our root file so import message from and we just need to navigate up to this folder a message and we come down here and we are gonna have another try and catch block and I'm gonna wait it because this is a promise so message dot create and we create a new model with a um we're gonna create a new entry in this collection in this message collection that's how mongodbs call it so new data okay so uh I'm gonna control lock this and it's gonna say message sent and if this goes good then I'm going to return um a response Nest response dot Json message and the message is gonna be a message sent and I'm going to also pass a status code which is 201 but if the recent error I'm also going to block the error message including message didn't couldn't be sent scent and I'm also going to return a response so nestresponse.json message error sending the message status 500. I'm going to return this okay so let's save this um come to let's come to the database first so in my uh let me just go back ahead here open collection so I have here all the collections I have from the for this project and this is the one that we are working with messages as you can see I have loads of messages at the moment I'm going to delete it yes let's just delete this completely drop and I'm gonna come here and um let's just give this a try and see if if our message actually is make its way through to the mongodb all right and let's come here let's just say hey there how are you doing actually let's just reload the paste unless you let me run the the project again because I think we made some changes in the amps file I'm not sure if I rerun the project okay and now I paste here my message send message let's just come to database okay email include is not a function all right let's just see dot email include okay I'm missing a yes here in the include this should be includes so if I save this includes unless you try again send message as you see okay now we have a different era but at least that past message couldn't be sent okay so all of this all of this validation is all okay then at to this point this is not going through let's just see why so we're supporting it this is schema that's fine here we are important but okay we need to just import it like this yes so we just import it like this now we are importing the raphaels let me just show you the message there are message it was telling us that has no Sports member so we so save it okay let's just try again send message come back and a different Arrow okay we are making progress database is connected but message couldn't be sent so there is an arrow here where Park imported module 2 create is not a function okay so create is not a function message create this smaller this is create new mongoose hmm hey I hope you are enjoying the content so far I'm finding it valuable for your career as you might know producing these tutorials take a significant amount of time effort and coffee if you appreciate the content and wish to show your support consider buying me a coffee it's a small way to say thanks and helps keep me energized to continue creating quality content for you every cap counts and I truly appreciate your support I leave the link down below and now let's continue with that tutorial I found the issue and it's here for some reason is not liking this operator the or operator so if I replace this for the um question question mark um I think this should work so basically what this is doing is if this is false then this is a fallback right so then we are going to compile the model before with the or it was like one thing or the other um not quite accurate actually and this would be the the right thing to say so only if this is false we will compile the module so let's save this oh my God there is so much noise where I am at the moment so I'm just gonna change to another microphone hopefully it's better okay hopefully this make it better let me just test it okay I think this should be better right okay cool so I think this should work so now if I save this um I come to the um to the application and let me just reload this page send message message has been sent and if I go to the um to database refresh test message as you'll see here the message yes hey there how are you doing how exciting is that it's a really simple and straightforward to way to connect your application with mongodb now you can have your portfolio or your blog or whatever you want and and get your users or your audience sending you message is really cool there are a few improvements that we could do it for example and when I'm here I can't send another message clicking send message but it's a bit confusing you know we don't know if the message has been sent because the page doesn't show any visual identifier that the message has been sent nevertheless if I come to the website we are gonna see that the message was sent but if we don't show the users something like that tells them this message has been sent the user is Gonna Keep clicking on send a message over and over and and then you're gonna fill up your your database with the same message so let's improve those things so for that but I would do there are like lots of improvements we could do but some basic improvements would be to completely reset the form of one that has been sent and also delete this message has been sent after a few seconds right so we give the user a bit of time to read that the message has been sent but then it gets reset reset and there are multiple ways of doing this I'm just going to do it in a really simple way in the faster way so for that I am going to add here a reference so form ref like this so I'm going to Define here the variable form ref and I need to use the hood use ref this book is a react hook so I import it from here use ref and now um I'm getting the reference to this form so I'm gonna create a used effect and I'm gonna say if um is message sent is true and we get this form ref you know we make sure that we get this reference first if this is true then this is just a cleanup function that we will actually need okay so let's just remove this need to import it and here um I'm going to reset the form so form ref current dot reset this is complaining because this could be a defined so I'm gonna add a question mark and this is complaining for the types we will add the types in a second so we come here let's see if we load and wait a second first I need to pass here the dependencies so this user fat I want this effect to run when this dependency is messy send changes so let me just remove this for now send message and the form has been reset have reset okay cool but I also want to remove these messages here because otherwise it looks a little bit weird right but to do that I don't want to remove it straight away otherwise the user won't see it so I'm going to create uh I'm gonna add a timeout so when you have time out you need a clip up clean up function so I'm gonna put this back and um I'm gonna create a variable using the let time out and it's like this and then here set timeout just gonna have a full back function and the time is going to be one second so here a is I'm gonna wait a a second and then this is gonna it's gonna set the set message sends two fulls I'm just gonna move this up to here and in the cleanup cleanup function I'm gonna call clear timeout and pass the timeout save this this is reload hello message has been sent and the form was reset and then the method the test has this that has disappeared maybe it's a bit too fast so let's add two thousand and let's try it again you doing message has been sent and now you disappear cool this is really good uh and um something else actually maybe we could add a bit of a transition when the test disappeared maybe it shouldn't disappear straight away we could add another time out but it's fine by it it looks good so let's just solve these issues these type issues so first this form breath this should be an HTML form element but the research terms that this could be a defined maybe we could put this or not and time out this is a node.js and timeout I think it is node.js dot timeout and yes that's it all the word means oh let me see nor or undefined okay let me just remove this yeah no so we are gonna have to specify and the file okay so my audio is still working for some reason but what I was doing here is I just removed that I mean the undefined I set it up by HTML form element or null and I set up the by default value as null so if while the Dom is rendering and we don't have the reference to the form the value is null otherwise once we have the reference the value the type would be HTML form um HTML element form and then I just test it one more time to say that everything was working and it was and now if we go to the database we can see that our new message let me just scroll to the bottom was submitted yeah this is really cool and really powerful I thinking these tutorials took us less than 30 minutes I'm not sure but it's quite amazing that we connecting our next year 13 application to mongodb in less than 30 minutes and now you can use this knowledge and for much bigger applications and that's it for this tutorial together we're taking our portfolio up from a static Json file file to a breathing mongodb database remember coding isn't just about writing lines of code is about creating innovating and most important learning and having fun so pat yourself on the back because you made it to the end if you found this content helpful consider sharing with your fellow coders so hit that share button and like button and spread the coding
Info
Channel: Time to Code
Views: 1,942
Rating: undefined out of 5
Keywords: next.js 13, nextjs, build a website with nextjs 13, build a website with nextjs 13 and tailwind, portfolio website, next.js portfolio website, next 13, next.js13, software engineering, app directory in next.js, mongoDB, next.js13 and mongodb, database, next js tutorial, next js, timetocode, time to code, nextjs 13, mongoose and nextjs
Id: Oiqj0jAvBQs
Channel Id: undefined
Length: 38min 8sec (2288 seconds)
Published: Sun Jun 25 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.