Mongoose Crash Course - Beginner Through Advanced

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
knowing the basics of mongoose is great for building out projects but understanding advanced concepts is going to take your code to the next level which is why in this video we're going to cover not only the basics but all the important advanced concepts and mangas that you need to know and these are concepts i don't see being covered in any other tutorial [Music] welcome back to web dev simplified my name is kyle and my job is to simplify the web for you so you can start building your dream project sooner and today i'm going to be talking all about mongoose beginner and advanced concepts and the first thing you need to know about mongoose is it's a wrapper around mongodb so if you don't already understand mongodb i highly recommend checking out my full mongodb crash course i'll link in the cards and description and also download this mongodb cheat sheet that i have it's completely free covers every mongodb command you need to know and that's important because all of these commands are available in mongoose i'm going to link this down in the description as well now to get started with mongoose we're just going to open up a blank project we're going to create a file called script.js you can call this whatever you want it really doesn't matter and we're also going to initialize npm so we're just going to say npm init dash y if you don't already have npm you need to install node to get that i have a video covering that i'll link in the cards and description for you once you've done that just type in npm i mongoose and that's going to install the mongoose library so we can actually use it inside of our project and the only other thing i want to do is i want to install another library as a dev dependency so we're going to say dash dash save dev and we're going to type in nodemon this is just going to automatically refresh our script file every single time we make a change which is going to be great so we don't have to keep re-running our script so in our package json let's change this test script to say dev start and we're going to change this to say nodemon script.js which is that file that we just created so now all we need to do on our console is run npm run dev start and it's just going to run the code in our script.js and every single time we make changes such as if i just put hi in here and save you can now see that's being printed out at the bottom of my screen so now we can actually rerun our code every single time we make changes now the first thing you want to do with mongoose is you need to connect it to a database so we need to get that mongoose library by requiring that at the top of our page and then in order connect with mongoose you can just say mongoose.connect and this just takes the url to your database if you have mongodb locally installed already you can just use the db url here which is mongodb localhost and then you put a slash and the name of your database our case we're just going to use a database called testdb and when we save we're now connected to mongodb you don't really notice anything because nothing gets printed out but this connect function takes two other arguments you can pass it in a function here and this is going to be a function that's called every single time you connect so we can just say console.log connected and now we save you can see as soon as we connect it prints out connected down here and then the second function you can pass this is like an error function so we can you know error out any message so if we fail to connect for some reason it'll print out that error down here but the nice thing about mongodb is even though it takes a while to connect to the database if you start using mongoose and interacting with your mongodb database it'll cue up all the commands you make and only make those commands after you connect so you don't have to worry about waiting for a connection because it'll do that internally for you which is why generally i just ignore all these options and just do a simple mongoose.connect now inside of mongoose there are three main concepts you need to understand the first concept is the idea of a schema and a schema just defines what the structure of your data looks like so if you have a user object you're going to have a user schema that says oh the user has a name and email and age of birthday and so on a model is just that schema in an actual form that you can use so a model is like an individual user object from the database that you can interact with and then we have a query and a query is essentially just a query you're making against the mongodb database those are the only three things you really need to understand about mongoose in order to use it and the most important of those is going to be the schema so to create a schema you could do it all in one file but generally you're going to have a different file for each schema so let's create a user.js file where our user scheme is going to live and we need to make sure we get mongoose pulled in so we're going to require that mongoose library so we can use it and then in order to create a schema in mongoose you can type in new mongoose dot schema and inside of here you're going to pass it an object with all the different options you need for your schema and we're just going to save this to a variable called user schema just like that so we can use this schema in a little bit now schema takes in an object and this object is just going to be key value pairs where the key is the name of the key in your mongodb object your database so if we want the user to have a name we're just going to give it a key of a name then the value of this key value pair is going to be the type this thing is so a name is going to be a string and you can use a bunch of different types we're going to cover them all in this video but for now we just have a user schema that defines a name field and that name is going to be a string if we wanted to add something else such as age in here we could just add that and then we say it's going to be a number type and this is where you put all the information for your schema all the different fields that it's going to take and so on once you've defined that then what you need to do is to create the model for that schema so what we can do is we can say that we want to do mongoose whoops mongoose.model and this is a function this function takes in the name of our model which in our case is user this is the name that you're going to see inside the mongodb database so this would be like a user collection inside of mongodb and then we pass it our schema so we're going to pass it our user schema so now we've created a brand new model which has the name user and it's going to be for our user schema now generally when you do that you're going to want to export that so we're going to say module.exports equals that model right here and then we can use that other places so now we have a basic schema with a name and an age for our user in our script js we can import that user model and we can say hey we want to require that dot slash user model that we just created that file we just created and now we have access to this user and if i just come down here you can say type in user dot and you're going to see there's going to be a bunch of different functions and methods that i can use on this user and the important thing to note is that a lot of the things you can do in mongodb you can do on this user collection so for example in mongodb you have a bunch of functions like find find one you know insert many insert update delete all of those normal mongodb methods that you have are all available on this user object the one that we want to talk about first though is going to be how do you create a new user well the easiest way to do that is just instantiate this as a new user object and you just pass it an object for example our object is going to be the keys that we want our thing to have so we want it to have a name of kyle and let's give it an age here of 26. so now we've created a brand new object with the name of kyle in the age of 26 but when i save you'll notice nothing actually happens because all we're doing is creating this user we can put them inside of a variable called user but we haven't saved this user to the database we just have a local copy inside of our javascript program but it's not in our database yet to do that we need to call the user.save function this is an asynchronous function so you can you know use then on the end of it and we could say you know right here console.log user saved there we go and if we save you're going to see it prints out user saved because it saved that user to the database now generally instead of using this promise syntax of dot then you're going to be using this in an async function so let's just create a simple function called run this is going to be an async function and then we can just use the await keyword instead of then it's a little bit cleaner to work with in my opinion and make sure this is all inside that run function and we're going to call that run function if you're unfamiliar with async wait i have a full video on it i'll link in the cards and description but now we can just do a console log of the user and if we just wait a second you can see down here we have a user with the name of kyle an age of 26 an id which has this random id right here and then this dash dash v so in mongodb you'll know that everything has an auto-generated id that's what this underscore id field represents it represents our id and then mongoose keeps track of versioning it's mostly for internal use so don't really worry about it but that's what this underscore underscore v stands for you don't need to worry about it it's just there for mongoose and this is the most basic way to create a user but there's also another way you can create a user by using the crate method on the actual user class here and we can just pass all the parameters we want to that crate method just like this make sure we await that and that's going to return to us a new user this await method right here this dot create does the exact same thing as say new user and save both of these are going to do the same thing so when we save you can see we get again a brand new user with the name of kyle in the age 26. another important thing to note is if you want to update a user let's say i want to change the user's name well i could just say user.name is equal to sally so now i've changed my local user object's name but i haven't changed the actual version in the database yet to do that i can just call that save method again so now if i wait this and save you can see the name here is sally and this is actually saved in the database it first creates a user with the name kyle and then it takes the name of that user changes it to sally and by calling save we're actually saving that to the database now this is obviously the most basic way you can use mongoose so now i want to jump back to our user schema and define a bunch of different other schema types right now we just talked about strings and numbers so let's add in a bunch of different fields here for example an email is going to be the type of string pretty straightforward created at is going to be a date so we can specify that we want this to be a date we can do the same thing for example for an updated at field so i'll put an updated ad here and i'm also going to come down below that and we're going to have like a nested object so we're going to have a best friend field and this best friend is going to represent another user so in this case we want this to be an object id you can see this object id right here so to get that we can just say mongoose.schema types dot object id and this is going to say hey this best friend is a reference to another object based on the id so this is an id of another user object then we can come down here we can say hobbies and this is going to be an array and to define an array we just take the array syntax and put the actual type we want inside of it so this is an array of strings if we left this blank it could be an array of anything and all that we want in our case though this is an array of different strings and then finally you can also nest things just like you can in mongodb so we have an address this address is going to have a street property which is a string and it's going to have a city which is also a string so now we've defined this user schema much more in depth we have all these additional properties and if we go back to our script here we can add a bunch of different properties into there let me just simplify this code a little bit put these on a new line so we can really see what's going on here and we can say you know what let's add in a hobby so we'll say our hobbies is going to be equal to an array and our array is going to have here weight lifting and let's put in here bowling now when we save you can see we have this hobbies array that has weightlifting and bowling inside of it or we could take our address and we could say hey you know what our address has a street and this street is going to be main street and now if i save you can see that this has that main street nested inside the address key now an important thing to note about nested objects like this is there's actually two ways to do it inside of mongoose you can do it like this where you just put the object inside or you can do it where you define a whole separate schema so let's say that we want to have an address schema and that's going to be equal to a new mongoose. schema and this schema is just going to be all the stuff from address so i'm just going to copy this up into this schema here and then we're going to say our address schema is for our address let me just make sure i have all my indentation correct there we go so this mongoose schema for address just has a street and a city and then down here we're saying our address is our address schema and you'll notice down here we just ran our code again by saving and you'll see that our address has that street but it also has this id property which is kind of interesting there aren't really too many differences between doing it this way with a schema or just nesting it directly inside but if you have a more complex object for example this address is pretty simple we could just nest it inside but if you had a complex object with a lot of other things inside of it sometimes doing nested schemas like this is the better route now the nice thing about defining everything like this for example strings and numbers and so on is if in my script for some reason i changed this age to be a string and i clicked save you're going to notice we get an error running and we can easily catch that error by just wrapping this all inside of a try catch so we can say catch and error and then we can put all the code for creating our user up inside this try and then the catch we can come down here we can actually print out our error so we could say console.log e dot message and now if i save you can see user validation failed age cast number failed for value whatever we passed in there type string at path h so it gives us an error message for the errors that we commit against this mongoose model so if our user is not valid when we try to save it or create it or update it it's going to give us errors for that and there are certain plugins you can install for mongoose to make these errors a little bit better so you can print them out to users because right now these are kind of long and complicated error messages but you get a bunch of other information for example if i say e.errors.age that's going to give me a bunch of information about this error you can see we have certain codes and we have actual values expected values all these different things you know the kind the value the path so we have super in-depth information about this error but generally 99 of the time all you care about is that error message so now let's fix this we're going to put our age back to how we had it before and i want to talk about some more in-depth validations because right now just having type validation is good but it's not as good as it could be what happens if we want to make sure a field is required let's say we want the email to be required well right here all we're doing is defining a type for it and if all you need to do is to find a type like our name string here that's fine but once you need to start adding additional things such as the required flag what you want to do is you want to pass an object instead of just a type and this object is going to take some parameters the first is the type so we want to make sure we pass the type as one of the keys so we're saying this email is a string and right now this what we have right here is the exact same as what we did for our name string it's just a longer version and it's going to work exactly the same but now we can add additional properties to our email for example we could say that required is going to be set to true and now when we save you can see we're getting an error because it says email is required but we didn't pass an email so now if we come in here let's just put an email in here which is going to be test at test.com and you can now see that if we just put the comma right here and save it's going to have that email there and we no longer get the error so we're using that required validation now one thing about emails that you'll know is that they almost always should be lowercase because it doesn't matter if they're uppercase or lowercase emails are case insensitive so you can actually say that hey this email should automatically be lower case by passing the flag lowercase with true now when i save you can see the email it saves as lowercase even though the email i typed in here had uppercase sliders inside of it it automatically made those lowercase and you can even do the reverse by doing uppercase instead and that would give us a full uppercase email but obviously in our case lowercase is what we're looking for now there's a few other types that i want to talk about for example on our created at we want this to be by default a date and we want it to default to the current date and time so we could pass this default property and for example we could pass in you know whatever we want here and we could say new date like this and it's just going to give us a brand new date as the default and when we save you can see this created out right here is a new date but the problem with this is it queries the new date once because it runs this code so it's giving us like a static value it'd be the same as if we typed in like five here as the default instead we want to run a function every time that we create an object we want to generate a new date so we could say like date dot now and now what's happening is every single time we save or create a user this default is being run to make sure hey do we have a value for created if not run this function and whatever it returns use that so now we're automatically getting the newest date every single time i want to copy this down for updated x i want to do the same thing by default my updated date should be the current date so now when i save you can see created at and updated right here are just defaulted to the current date while we're on the topic of this another important thing you can do is use the immutable flag so we can say immutable set that to true and now that means we cannot change this created at at all it'll never let us change create it at even if we're inside of our script here and we try to say hey you know what user dot created at let's say we want to change it to like five for some reason it doesn't really matter we're changing it to something and now we want to say await user dot save and if we save you're gonna notice nothing happens we don't get any errors and this created out here has not changed and that's because when it's immutable it just ignores all the times that you try to set it to anything it'll just never let you set they created that value now the last two main built-in types i want to talk about are for minimum and maximums for example we can specify a min and max number for our age so we can say that the type here is number and let's say we want the min to be one the you know the youngest you can be is one so if inside of here we put our h was a negative 26 we're going to get an error that says hey it must be at least one that's the minimum value we could also put in a max and say like 100 to the max and if i try to tell myself that i'm 260 we're going to get an error saying it's over the max of 100 and you can do the exact same thing with strings so for example we could say our min length here whoops length is going to be 1 or let's make it 10 for some reason so that says our email must be at least 10 characters long so if i make our email shorter you're going to notice we're going to get an error if i just get rid of this error here that says our email is shorter and it must be at least 10 and you can do the same thing for maximum and the last type of validation that i want to talk about is going to be validation that's built around custom validation that you write yourself so let's say on our age we want to add some custom validation well you can use a validate object here and this validate object you're going to pass it a validator so we're going to say validator and this is a function that runs to check if this value is valid so it's going to take in a value and we just return true or false so let's say that we want to make sure this number is always even we could just do mod 2 here that's going to check is this number even if so true otherwise false and then we can also specify a message and this message takes in this props object and this props contains the value so we could say for example props dot value which is going to give us whatever our ages is not an even number just like that so now when i save this and we come over you're going to notice that we actually get an error and that's because this should say equals zero that's going to actually check if this is an even number or not and now you can see it's working but if we change our age to 27 we're gonna get an error that says hey 27 is not an even number so this is really nice because you can do all this validation on the model itself which means you don't have to worry about writing this validation code all over the rest of your place it's all in one spot and it's going to give you nice errors that you can use everywhere else now there is one issue with all this validation though built in or custom it doesn't matter it's only going to run when you use the crate or the save method and so far we've done everything with the crate or save method so you're probably thinking that's not a huge deal but there's a bunch of other methods built into mongoose that you can use to update things in your database without using the create or save methods and those don't go through validation because they work directly on the mongodb database so let me talk about some of those different methods as you can see when we say user dot we're going to have a lot of different methods that we can choose from here and a lot of these are for querying information for example we have find or count and so on we have create right here that we talked about but you'll also notice we go a little bit further we have these sections such as find by id and remove or and update or and delete and same thing with here and update and replace for find one and these things where you do like find one and update or if we scroll down a little further where we have functions such as update one or update many those do not go through validation which is why i always recommend you do not use these methods i'd recommend always doing just a normal find by id or find one get your user and then call save on that user don't do the find one and update or find by ad and update because that's going to skip all of your validation now i do want to talk a little bit about how you use some of these query methods though like find by id and find one so let's just comment out or get rid of this code that we have here for now and i want to just copy this id that we have so this is an id of the object that we just created most recently so i could say user dot find by id pass it in the id right here cons user equals awaiting that and this is going to give us a brand new user and again this is all asynchronous code returns promises console.log user and hopefully this should get us this exact user we just created so when i save you can see it returns to us the user that contains that exact id that we just queried for super useful now if you want to do a little bit more of a generic query you can do the find method and the nice thing about this find method is it works identically to how it does in mongodb so i could say hey i want to find where the name is kyle and now when i click save that's going to give me a bunch of users so if we look in our you know console you can see we have a bunch of users because everything we so far have created has been with the name of kyle now if we were to search for a name you know that doesn't exist such as s and we click save and we scroll down you notice we're going to get an empty array so this query method like i said it works pretty much identical to mongodb so if you understand how mongodb queries work it's going to work super well you can also change this out for find one and if we put in here for example kyle you can see it's just going to find us the very first one that has that match so we're going to just the first user with the name kyle we also have methods such as exists and this is going to say hey does something exist that matches this so for example yes we do have at least one user with the name of kyle in our database and then we have those other things you know we have like find one and delete and remove and replace and update i recommend again don't use these and you also have things like update one again i wouldn't use that but one that is really useful is delete one and this is going to just delete whatever matches the first thing that matches is going to be what's deleted or you could do like a delete many and that's going to delete everything that matches the query so we could say like delete one right here that doesn't actually return to us anything useful but here we can say delete one where the name is kyle and we're going to save and that's deleting one of the users with the name of kyle and we can just see what this returns to us as you can see it says deleted account equals one because it deleted one person now one thing about mongodb that is a little confusing is the syntax for the find method is kind of confusing to mongodb which means it's confusing in mongoose which is why mongoose implemented something called queries a query is where you can say dot where and this dot where allows you to essentially create your own query your own find syntax based on a bunch of really nice helper methods so let's say hey we want to check where the name is equal to chi well we could say word name equals kyle and this is going to do the exact same thing we did before as you can see return to all the users with the name of kyle we could say hey i want to check where the age is going to be greater than 12 and now we can do that and again we get all the users with the age greater than 12. you can also just continue to change these together so we could say oh you know also i want to check where the name is equal to kyle so now it's going to say hey where the age is greater than 12 and where the name is equal to kyle and again of course we're getting all of our users being returned and we can keep chaining this together for example also i want to get the users where the age is less than for example 31 and let's just make this an actual number not a string and again we're going to get everything because everything's less than 31 but if i change it to 21 you're now going to see we get nothing because there are no users where the age is between 12 and 21 and the name is kyle we get rid of this lesson real quick we'll get all the users being returned but we can also put in a limit let's say we only want two users now limit two we're getting two results being returned to us we can also do a select which says only get certain fields so let's say i only want to get the age field so now i'm going to get the age field for those two objects and that's the only thing being returned now the final thing with queries i want to talk about actually requires us to modify our schema so if we go back into our schema let's scroll down to where we have this best friend i want to expand this so our type here is going to be an object id and what i also want to do is i want to specify a ref and we're referencing the user model this ref tells mongoose hey what model does this object id reference in our case we're referencing the user model because this is just going to be a reference to another person in our database and now what i want to do is i want to add a best friend to one of our users so let's just come in here we're going to say that we want to you know just limit this to one so we're going to have one user so we're going to say user 0 dot best friend is going to be equal to and i want to just equal that best friend here to this id so we're going to paste in that id and then i'm going to save them so we'll say user 0 dot save here make sure i put this all correctly there we go dot save make sure that we await this and there we go we saved that real quick now they have this best friend right here so now we access that user let's get rid of this select here and we're just going to be getting that user let's get rid of this code here so we're getting that user that we just updated and when we click save you're going to notice they now have that best friend which has an id what we can also do is we can use something called dot populate and we're going to say we want to populate the best friend field and when i say if you're going to notice something interesting now that best friend instead of just being an id has all of the data for the actual best friend object and that's really cool because in mongodb you can't really do joins very well so mongoose has this populate method which essentially allows you to do a join it's saying hey for all the best friend ids inside of this model and all the other models go and find that object and put all the data for it inside of this best friend section so now we can actually do a join without really doing a join it's a really cool feature of mongoose now this right here is a lot of the more basic features of mongoose so now we want to start talking about some of the advanced things you can do related to schemas which really can make your code take it to the next level so let's go over to our user model here you can see we defined everything in this schema let's just minimize this because we're not actually going to modify the data in the new schema we're going to be adding stuff onto our schema afterwards one of my favorite things that you can add is methods so i could say hey user schema and i want to add essentially a method onto each instance of our user so when we query a user here for example if we just say user dot find one and we're going to get one where the name is equal to kyle so it's just going to give us one single user if we scroll down here we have that first user with that name so what i want to do is i want to add a method onto every single instance of our user so we can just say user schema.methods and then we put dot whatever the name of the method is in our case let's make this method called say hi and we set that equal to a function and now the important thing in mongoose is that you cannot use an arrow function here you must use an actual function and that's because in this function you use this to reference the actual individual instance you're working with so let's say here we're going to console.log we're going to say hi my name is and then we're going to print out this dot name and it's going to get the name for the individual user so now all of our user models have this new method called say hi on them so now what i can do here is i can say user.say hi and now when i run that you can see it says hi my name is kyle and we added that in our schema now you probably thinking wow that say hi method is useless and you're right but these methods are really good for when you want to just do a bunch of different things related to your model and you don't want to have to define that code everywhere you can just define it on your model itself now you can also define static methods that are going to be available on the actual model so not the instances but the overall model itself so when you do like user dot find you can create your own methods that do similar things so to do that you can say user schema dot statics this is going to be for defining these static methods and we're going to call this find by name and again set that to a normal function and inside of here we're going to pass a name to this function now inside of this function what we want to do is we just want to return essentially a new query so we're going to say this dot where the name here is going to be a regular expression so we're going to use regular expressions and we're checking for the name and we're just going to make sure this is case insensitive so what this simple set of code right here does is we're doing a simple where query and then we're taking our name we pass in passing it to a regular expression just so it's case insensitive and we're saying get all the users that have that name so find the user by that name and now when we click save we can actually use this method so inside of here instead of saying find one where the name is kyle we can say find by name and what we can do is we can pass in that name of kyle and we should hopefully get the exact same result being printed to our screen and you can see that we have this kyle object being printed out right here and it's actually getting us a bunch of different users which is why users say hi isn't working but as you can see here we're getting a bunch of different objects being printed out because it's giving us every user with that name kyle you'll also notice over here i used a slightly different syntax for wear and that's because ware can also take essentially the same thing as a find you can do it however you want now on top of this we can also add things to our queries themselves so right now we added things to our like user dot but what happens if you want to add something particularly only to a query we can say user schema.query and here we can do like by name that's going to be equal to a function and we're going to pass it in the name and this is going to be almost exactly the same code so i'm just going to copy this down here paste it right here and actually up here we have find by name i'm going to change this to find instead of where so it's going to be exactly the same but this is just going to say find and this is going to say where and the reason for that is because this is going to be chainable with a query and this i just want to return i don't want it to actually do any query related stuff so now when i save we now have this by name method that we can use as well so in our script we can say user.find and we want to find by name which is going to be kyle so now when we save you're going to see we get all the users with that name but you'll notice we can't call by name directly on the user it's actually going to give us an error says by name is not a function and that's because when you use user schema.query we're only putting this method on the query and the query is returned when you call something like dot find or when you say dot where that's going to return to you a new query that you can use which is where this like buy name is going to come in and for example if we wanted to say like find by name this is only available on the actual user itself so you cannot do it as part of a query so it's kind of interesting they made this distinction you have to kind of to figure out do you want this to be a static level method or a query level method now the last thing i want to talk about is probably my favorite thing and this is something called a virtual so we can say user schema.virtual and how you define these is a little bit different you're going to pass this a value and that's going to be the value of the name of your virtual so we're going to call this named email and this is working very similar to like user schema.query.by name this named email is the same thing as like by name or find by name it's the name we're giving this virtual and a virtual is essentially a property that is not actually on the actual schema itself but it's a virtual property that's based on other properties already on there so we can give this a get and a dot set so let's just give it a get here and they got git again takes a function and remember you cannot use arrow functions in this function we just return a value so we're going to say hey you know what we want to return here this dot name and then we want to put the email inside of these brackets so this dot email just like that so now we've created a named email property so this is just a property that exists on an individual user so let's say that we want to find one and we want to get them where the name here is kyle let's just go back so we have one user and i want to say user.named email and i'm going to console.log that out now when i save you can see down here it's saying kyle and undefined that's just because we have no email on this user if the user did have an email though the email would go right here so let's say also where the email is test test.com now you can see we got it says kyle and then it puts the email into this section but you'll notice on our actual object there is no named email property this is a virtual property so it doesn't get saved in the database it's only available inside of our code and this is great because you don't want to save this named email property in your database because it duplicates all this data but you probably want to use this all across your application so this virtual is the perfect way to do that now i know we've covered a lot so far but i have one final topic i want to talk about which is middleware inside of mongoose if you used express you're probably familiar with middleware but middleware and mongoose allows you to insert code in between different actions for example saving a user or creating a user and there's going to be middleware that covers saving validating removing and update one don't really worry about the update one really the only middleware you care about is going to be save validate and remove so in order to create some middleware you want to take your user schema and you want to say either pre or post so if you want this middleware to record before the thing that we're talking about you use pre so if i want to do some middleware before i save my model i'm going to use pre and then i say save so this is either going to be save or something like validate here or it's going to be removed so if you want to like do something before you delete something use remove or if you want to do it before you validate use validate in our case we want to do something before we save and we want to run a function and this function takes in the next property and just like normal middleware you call this next function to move on to the next middleware if you want to do that so here all i want to do is i want to take my updated at and all i want to do is set it to date dot now i just want to update my updated out to the newest time and then call next so what this does is it says every time i go to save a user i want to take this updated field update it and then continue on with the rest of my code go on to the save for example if i left this nest out it's not actually going to move on to the next thing in line so now by doing this if we were to update this user you're going to see that it's going to update that updated ad field for us so right now the updated app field here is you know 20 21 11 05 and we have 1704 28. now if we wanted to come in here we say user save and we make sure that we await this we should see that this updated time is in incremented and we're going to make sure we console.log the user down here below it and now when we save you can see this updated time is o 457 and before if we scroll up here a little ways you can see it was o 428 so it has been incremented to the newest updated at time we can also do a post for example if i come into here i can just copy all this code we're going to do a post save so we're going to change pre to post and this is going to happen after the save and here all i want to do is i just want to say this dot say i but we actually cannot use this because instead it's going to pass to us the document that's been saved so here we can say doc dot say hi and this doc right here is just the user object the thing that has been saved now it's going to say hi and then move on to the next piece of middleware so now if we go into our script and we just save this if i scroll all the way down here you can see it says hi my name is kyle and that happens directly after save so it's happening between this user log and the one below it now these middleware are great because they allow you to actually make sure things go on so if you don't want to allow save you can just get rid of this next right here and now you're going to see that this save fails and in order to actually show you how that's failing let's just put in here an error so we can throw a new error and let's give it a message of fail save now we click save here you can see it's printing out fail save and that's because here we're catching that error and printing it out here if i get rid of this console.log user it's easier to see it just says fail save so by throwing an error we can say hey you know what abort this save i don't actually want to do it and that's great for these pre-save pre-valuate post save and so on and that's everything you need to know about mongoose also if you want to make sure you take your mongodb game to the next level you're going to want to download my free mongodb cheat sheet linked below it's going to help you with mongodb and mongoose so i highly recommend it that said thank you very much for watching and have a good day
Info
Channel: Web Dev Simplified
Views: 34,737
Rating: 4.981132 out of 5
Keywords: webdevsimplified, mongoosejs, mongoose js, mongoose node, mongoose mongodb, mongodb nodejs, mongodb, mongo nodejs, mongodb node js, mongo node, mongo node js, mongodb node, mongoose node js, mongoose nodejs, mongoose tutorial, mongoose js tutorial, mongoose javascript, mongoose javascript tutorial
Id: DZBGEVgL2eE
Channel Id: undefined
Length: 33min 35sec (2015 seconds)
Published: Tue Nov 23 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.