Nest.js with MongoDB - Complete Example

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi and welcome to this video in my first video about nest reyes link below the video of course I introduced you to nest Ches I explained what it is and we built our first little application a first little API with nest Ches now in this video we'll build up on the project we built there but the code is provided below the video in case you didn't follow along and we'll now connect this application to a real database we'll connect it to MongoDB and you will learn how it works and how you of course may use it in your own apps thereafter so let's dive in so in this video we're going to connect our little nest chase application which we worked on in the previous video which you should definitely check out link below the video of course we'll connect this application to a database to MongoDB now for that in case you don't know what MongoDB is I do have a link in the video or two links actually where I explain what Longwood EB is and also where I compare MongoDB which uses as no sequel solution to sequel databases so that might be helpful so for the rest of this video I'll just assume that you know what one would be B is and for this video I will use their cloud solution MongoDB Atlas that simply means that I get a fully managed database in the cloud you don't need to pay anything for that for the basic version of it at least of course there are paid versions but for the basic version which will suffice for this video you don't have to pay anything and long DB Atlas simply is very convenient to use make sure that we don't have to install anything locally and so on now here I'm already locked in with my account which I created up here with sign-in and there you can create a new cluster and you can basically leave all the defaults or choose the free care settings wherever you're prompted so that you get a cluster which you can run for free again for the things we're going to do here now cluster simply is like your cloud database for actually a collection of databases to to be concrete and we can connect to this cluster from inside our nest jeaious application now now for connecting a node application to MongoDB be that a local MongoDB instance or wherever MongoDB Atlas as it's here you got two main options version one is that you use the official driver you can find that driver by simply googling for MongoDB nodejs and what you'll find there in the end is this MongoDB package which is the official Longwood EP driver and you can use that in any node app and therefore also in an SAS application and that would allow you to manually connect to database and then run queries against the database definitely something you can do not bad but of course means you have to write all queries manually if you want to insert something you have to write the full query manually if you want to fetch data and so on there is a more convenient way of doing that and that's the way I will use here we'll use a package called Mongoose and you can find your official docs on Mongoose Jess calm Mongoose is a nodejs package which wraps the native driver so which wraps the one would he be packet we just had a look at but gives you more convenience functions to be precise it's a model focused packet where you work with models which in the end are JavaScript objects and then you can save something to the database through these objects or get some data from the database with the help of these objects you can check out the official Docs to learn all about this package and this is the package will now use as well now for that we first of all need to install it so here in the command prompt or a terminal in your project folder you can simply run npm install - - safe and then I will install Mongoose but there is an error package which I'll install there is a nest J's wrapper so we'll all install at nest Jaya slash Mongoose now this simply helps us use Mongoose in this app we wouldn't need it we could technically use Nair Mongoose without this nest J's package but with the nest as package we get improved typescript support we can inject things to make our lives easier so I would definitely recommend using both now with that installed let's set everything up and for that we first of all could connect to the database that seems like a logical first step I'll do this in the app module because you connect to the database by importing something from this Aetna's chase mongoose package and that's something which you do import there is the mongoose module the mongoose module can be used to set up a database connection and it makes sense to set this connection up in the app module which is our first module to run and to be loaded because I want to connect to the database as soon as possible when the server starts so here I'll now import mongoose module and there you call for root which is a method provided by this module your esthetic method to which you now pass your action string and that connection string if you're using MongoDB Atlas you can be found here under connect connect your application then it's this string here so I'll copy that string close that and then enter this here as a string now a couple of important things about that string this string includes the user name for which you want to connect and a password for this user name and both needs to be managed by you you can do that here in MongoDB Atlas under database access if you click on that you see your users there I actually want to use this Maximilian user so I'll change the user name easier to Maximilian but of course you could use any net user you want you just should make sure that it has at least read and write database access and I'll also set a password which I'll change after recording this so no need and copying it and I'll enter this password here you could use environment variables if you prefer that for our purposes here this hard-coded connection string will do at the end of this string you also to find the database you want to connect to because as I mentioned the cluster holds a combination or multiple databases and I'll use nest Jas demo as a database name the name is totally up to you if it doesn't exist yet it will be automatically created so instead we got the connection string setup and when we now start this application nest share should actually try to connect to our MongoDB server here now that's a nice first step but of course we can't do anything with that alone instead we now need to add code that allows us to add data to the database or to fetch data from there and since we're using the moongoose package we'll use the moon whose package for that because as I mentioned this mongoose package allows us to work with javascript object and it runs the database queries and sets them up behind the scenes so we don't have to write all these trees manually instead that's done for us so to say now for that you need to understand how mongoose works and of course you can check out the original docs to learn all about mongoose mongoose works with so-called models which are nhien blueprints for the javascript objects you then create which are these enriched JavaScript objects which represent your data for example a product object which is not just a product object based on a class like this which is just a bunch of properties but instead since Mongoose will help us create this object it will be an object with a lot of behind-the-scenes magic that will run queries automatically and so on now all these objects are based on these mongoose models and these models on the other hand are based on Mongoose schemas and a schema simply defines how a model should look like regarding the properties it has so therefore in this product model file I'll now actually add a new thing and we'll add such a scheme and verdad well first of all import everything as Mongoose from the Mongoose package and there we will now use Mongoose dot schema now I want to store an export this schema and I'll name it product schema and this will be the blueprint for the model which then is the blueprint for the concrete objects but that's just how Mongoose works there we create a new mangu schema so that's a constructor and now here we pass a JavaScript object where we define how a product object should look like and we're setting this up for Mongoose so to say now of course we'll have the same properties as down there except for the ID because we actually don't need the ID we'll have a ID which will be automatically generated by Mongoose and MongoDB so we'll only focus on the free other properties we'll have a title now without public because this is now a JavaScript object literal here this is not a class were defining with the help of typescript so we can't add public here instead this is a title and now for Mongoose there's something special you also have to define the type of data this is but you don't do this with these typescript types because Mongoose doesn't use typescript instead you do that with the default JavaScript types therefore of course it supports different types than typescript does and they're also sometimes written a bit differently for example they're written uppercase so if that's a string we have to define it with string like this and not string like this this is the typescript type this is a JavaScript type now besides the title we'll have the description which of course is a string and then the price and the price is a number but with a capital n now for Mongoose you can also be a bit more detailed than that you could pass an object instead of just a type name and there add a type property which describes the type and then in addition for example you could set require to true to indicate that this is a required field which always has to be provided and I will actually do that for all three fields here now we have our product schema and that's important step because now we can create a product model based on that schema now we do have a product model on there but this is not the model we'll continue to use and I'll come back to that in a second instead now we go to our products module and there we can now add a imports array because you set up a mongoose model with the help of mongoose module so again we import mongoose module from Aetna's chess mongoose like that and then here in the import now of the products model not of the app model I will setup mongoose module dot for feature and then has some data here now the idea here is that this will automatically allow us to then inject this model a to any file that needs it so you can share this model which you're creating with the help of dependency injection that is what mongoose module does for you it creates that model and makes it injectable it takes an array because you could define multiple models which are available for injection in this module so in this products module but here I only have one each model then is defined with a JavaScript object where you give that model and name name is up to you but of course it should make sense for the data you're managing so here I'll name it product and that has to be a string and then you have to point at the schema that defines how the data should look like for this model and that of course is our product schema here and for that you need to import product schema from the product model file so with that setup were defining this model we're making it injectable with the help of Mongoose now we can inject it into files where we want to work with it and that would be the product service of course because here we are for example creating a new product and right now we're doing this with our own model this will now change and we'll use the Mongoose model because that will allow us to create JavaScript objects but magical JavaScript object so to say where we can then also call a simple method to write it to the database and have Mongoose do the heavy lifting for us so all we have to do here is add a constructor because as I just said we can inject these models these mongoose models and q inject this model we now need to again import something from Ness j/s mongoose so from Aetna's J's mongoose we're importing and there we're importing the inject model decorator in the end which is you can use this in a constructor at inject model this simply tells nest chess that you want to inject a mongoose model q inject model you pass a string and that is the name of the model you want to inject here that's of course product here because I defined that product should be the name of my mongoose model here in the products module we have the product model setup here we can inject it here now you can store this in any argument you want like product model but I also want to use two types of shortcut off automatically storing this a property by adding an accessor in front of it and we can also add to read-only modifier here to make it really clear that we will never overwrite the value which is stored in the product model property here now this also has a type and this type is of type model which you have to import and you import that directly from Mongoose so not from nest Reyes mongoose but from just Mongoose you import model and model actually is a generic type because model is that base class Mongoose uses which holds all the magic for running the queries the concrete model then also needs to take your schema into account so what you pass here is now a description of how your model looks like that's something we're missing we're defining our schema here but that's not really a typescript thing here that's as I said just set up for mangu is using Java Script types and so on but we do have our own model here now we could turn this into an interface instead of a class the difference is that we now can't if a constructor we can't instantiate interfaces an interface is simply a type description if you will and therefore here we would now just have our properties like this so we can add all of the adds get rid of public here and now define an interface like this and ID will be auto-generated in the end and whilst this technically will be stored in an underscore ID property there will be an ID gather later which allows us to get the ID with just the ID Cillian that will return a string so that gather so we should have this as a product object which Mongoose creates for us and now in the product service here in the generic type for mod we can therefore refer to product and simply import product from product model as we're doing it before now we're injecting this product model which is created by Mongoose and now we can start using it and let's start using it for creating a new product now here we're creating a new product by calling new product now this should now be new this product model looks a bit strange but product model is a property hence we have to use this and then we can use it as a constructor again it's created by Mongoose and what Mongoose in the end creates here is a constructor function and that's basically the same as a class or follows the same idea and therefore we can call this or use this with the new keyword to create a new object based on this blueprint created by Mongoose behind the scenes now to product model we don't pass four different arguments though instead we pass a JavaScript object which should provide the fields we define in our schema so a title description and not an ID because that will be generated automatically so we don't need to create our own ID here instead we provide title here and title will of course hold the title value which we're getting we do the same for description which gets the desk value and price which gets the price value if you want you can shorten these assignments here where the key name and the value name is the same you can then use a types code shortcut here and in the end we'll MIT this value assignment behind-the-scenes this will be expanded to this syntax but it's a bit shorter for you to write so with dad here I'm setting up title description price on this mall I'm creating a new object based on this model which is stored a new product now we're no longer going to push this to some local array here instead we can now use new product and to save it to the database all you have to do is call save this save method was never defined by us it is provided by Mongoose instead and that's what I meant it's this magic behind the scenes since Mongoose creates this model it does not just wrap our schema but add these extra magic methods to it and these extra magic methods like save will create a full DB query behind the scenes which saves our data to the database now of course here we want to return the product ID though for that it's important to note that safe in the end will return a promise so here we can use then or use a single wait which is what I'll do simply at the async keyword and set in front of insert product now we can await this case you don't know that syntax it's an alternative to using then here in the end it makes the code more look more like a normal synchronous code it's still using promises in their product now we'll also implicitly return a promise we can add async in front of here and therefore use the await keyword to wait for this promise to complete before the next line executes behind the scenes the code after this line simply gets wrapped into an invisible then block here so here I await the result and then I get my well result here and for the moment I'll not return any thing here but instead I'll simply console.log results so that we can see what's in there actually it will return something but I'll return a hard-coded string for now which is of course not the ID we're getting back with all of that let's give it a try and we can run this with NPM run start : death to bring up that development server let's see whether that works the way it should work so it's trying to connect and it's having issues here connecting reason for that is on MongoDB Atlas setting up the user is one thing you always need to make sure that you whitelist your local IP you have to whitelist your local IP if you're not doing that then MongoDB Atlas will block access from your IP that's a security mechanism so make sure the under network access you add your local IP now wait for these changes to be active before you try again in the meantime I'll already bring up postman here because will of course need postman to send post requests to create a new product for example here I already got it prepared it's the same post request I sent in the last video so I got it prepared there's now also finished now let's try running this again now it should be able to connect to MongoDB Atlas and yeah that's looking way better this is up and running now let me send that post request I sent this I get back no ID which kind of makes sense when I do get here in the console looks promising though I get this object being printed and there we see our data and we see underscore ID which I mentioned before is this auto-generated ID stored in the underscore ID field and if we now have a look into our database here in MongoDB Atlas under clusters collections you can also download MongoDB comp s and connect that to your cluster if you can't access the collections like this but there I can look into my databases and into the data store there and there if I go to the nest chess demo there's the products collection it has one document so that looks good because we we entered one document and there indeed I see the document I just added so saving works and as you see we had some initial setup but now it's really simple it's just this call of the save method now we also know we're getting back a result there we have the ID and underscore ID but as I mentioned the result will actually also have an ID getter so what we can return here is result dot ID in the end because we know that this ID field will be available so now if I save this again and I give this another try with a first product this is our first product and sent this I still get back ID nothing here so we still have a problem so look at the controller we should be getting our generated ID but yeah there is one issue and it's it might be tricky to spot as I explained save returns a promise right and I'm using async await this Mexico to look like it's synchronous code but it isn't as I said the line after this line is simply wrapped into a van block now since we return here returning inside of a van block typically wouldn't return for the overall function so what happens here is that this technically here returns a new promise which the overall function returns at that overall promise will then yield the data you returned here so this overall function returns a promise hence in the controller where we reach out to insert product in their product now returns a promise we also see that here now since this returns a promise here we have to handle this IVA with then or by also using async await here and I'll do the latter so add a Singh here and then I'll wait this and now we get this back because now this will wait for this promise to complete before it didn't wait it did send the response immediately before this promise completed which is why we had no idea in there so that's an important adjustment and now whenever adjusting I'll make is in a product service type script isn't fully able to understand what insert product yields in the end it's a promise but it doesn't know which day that this promise resolves to we know that it of course will resolve to a string so what we could do here is we could add a string here and now we would have the correct type and Firenze here which definitely improves our code a little bit so with it let's save it and let's give it one more try let's do a second test with a second product here and if I sent this now we get back the newly generated ID here so this is now looking better and if we have a look at our collection and we refresh this here now we see free documents in there so that's how we can save data what about getting data in the products controller we have get all products and that's what I want to start with so we need to work on get products in the product service get products before just returned our array now that's of course too simple because now it's not just about returning an array instead now we want to return well the result from our database now again for this we can work with this product model so with this product model but now we don't create a new object based on it but this model being created for us by Mongoose also has some magic static methods for example the find method which allows us to well find data so now find will also get us some data and find although should yield a promise so let's again use async and a weight and let's see what our result here is let's console.log it so that we can get an impression so let's call the lock result here go back to get and get all our data now here we get an empty array of course because we haven't adjusted the our logic but in the console here we indeed see an array with free documents so that's looking good now since we know that result is that array products looks like a more fitting name here you can of course name this whatever you want and I don't want to log it but I want to return it so here I want to return my array of products in the end now one important adjustment by the way find does work like this but actually does return a real promise it only does so if you call exact after this it's a tiny improvement which I would recommend doing viryx otherwise as well but this gives you a real promise and therefore simply is a a bit better so now we still get our products here we could now return this products array which we just fetched we don't need to copy it anymore because it's created and new here anyways it's a fetch from database and a new products array is created here so no real need to copy it we're not managing here in memory so we can return our products and in the products controller where we get all products this now of course all the yields a promise promise off type any because again it's not able to infer what products looks like we think we can be clear here we know that it's a product array so product is my own interface here towards describes how a single product looks like and that's our array of products so now types could knows that get products returns a promise which eventually yields a list of products an array of products so in the products controller since this now returns a promise which eventually gives us the products array this has to be a sync or you can always of course use then and return a promise here but here I'll go with a sync and then all I'll wait my products here and then simply return products like this now let's see whether that works the way it should if we save this and I resent this request now I get back my products here now one tiny adjustment you see the ideas stored an underscore ID and we have two strange we thing here and I actually would like to have ID here instead of underscore ID that's relatively easy to do here in the service we can transform the data we're turning a little bit so that really fits our product description because now our product interface we're saying that a product has ID field not underscore ID and then only title description price and whilst it technically works even if we have the extra underscore we thing and a different ID name it's not really what I want to have so let's go back to the service and let's transform the data before we return it we can do that here by calling products map because product is an array so we can call the built in map method which is provided by JavaScript this takes a function which it runs on every element in this array which we get as argument therefore and we have to return a new element and the new element here should be a new object which should adhere to our product interface or which basically be based on our product interface so I want to have ID we get that from prot by calling ID as I said there is a quatre which gives us that ID it's not a property but I gather which Mongoose gives us on these object it returns then I want to have a title and that is broad dot title and I should wrap this here in brackets by the way to have a valid syntax where we just return an object in this inline arrow function then we have a description with prot description and we have a price with prot price so now I am mapping the data we're fetching from the database into this new format which I'd then return and now if we save dad and we fetch our data again now we see we have just ID here and we don't have that underscore underscore V thing a minor thing but still definitely something that makes sense here I guess so instead let's move on let's make sure we can also fetch a single product for dad we have to get single product method of course we don't call this find product anymore or we might but in this find product we definitely don't want to find a product in our array anymore in our local array but instead we want to find a product in the database and actually we don't really need find product like this because the index and so on that's not something we really need here so I will change this this will now just return a product nothing else and for that up here where we get our product I want to reach out or I want to use this product model again this model created by Mongoose and there again fine but now a slight variation of that find one find one is extra method that exists for cases where you know that you really need only one item that allows Mongoose to not scan all your items in the database but stop after it found the first one now found the first one that's something I'm saying because now we'll add a condition to find one we could have added one to find as well to only find products with a title of something or with a price of something and you can learn all about the different ways of writing queries and writing conditions in my mom would EB course if you want link to dead all below the video but here we'll have a very simple condition we'll find one we'll find one by ID for dad Mongoose actually has an even batter method we can use fine by ID which is a method provided by Mongoose where we just pass in the ID which we're getting as an argument here and then Mongoose will find us this element in the database and return it now of course this is asynchronous so let's add the async keyword and then await the result here and therefore here we don't return a product but in the end a promise which yields a product the correct type description would be this and here we get our data now if product is not the fine thereafter we still can throw this exception still make sense at this point here but here of course I'll now just return product though now just as before the product we're fetching would look a bit different it would have underscore ID ins on so let's actually return a new object here where ideas product ID title is product title description is product description and price is product price and now what we have here is again a transformed object which looks like our product interface so let's define product helper method we can now use that here in insert not an insert excuse me in get single product of course this fine product we no longer need to access the first element of the return data because we're not returning a tuple or an array anymore we returning a promise instead so instead of accessing this which has to go let's Robert turn this into a async method so that we can use our weight here to find a product store that in product and then return it no need to copy at first we can do it like this and yeah that should be good now to avoid errors for the moment down there I'll comment out the code in update product so that we can save and test this without the app thrashing so let's give it a try let's try fetching a single product and for this we can copy such an ID here and then go to this get method where we fetch a single product enter the ID and hit send that's looking good now let's try an ID which doesn't exist by simply modifying this slightly and we get an error here now we're getting this error because cause to object that you failed that part ID for model product and yet the problem here is that fine by ID expects a valid Mongoose ID and this isn't a valid Mongoose or a valid MongoDB ID and it can already tell that this is not valid so what we should do here is we should wrap this into a try-catch block to catch such errors as we're having it here and then handle it for example here to still throw our own not found exception to return a better error message instead of have our server crash of course that means that product isn't always set so let's set product to a variable here and override it here in try-catch so that even after this try catch block we always have a product it might just be undefined which were handling here and now let's try saying this request again and now we get a 404 error now let's try using a valid MongoDB database but still one which doesn't and we get a 404 error in this case as well and for a valid ID we still get the product so fetching single products and handling errors all the works let's now move on to the next method which is for updating a product now for updating a product I'm calling update product in my service and an update product in the service in the end what we're doing is we're first of all fetching the product from the database we're thus far from the local array but now we'll have to fetch it from the database and then we can edit this product and save it back to the database that's the plan updating is super simple with Mongoose first of all for that you fetch your item so in this case our product and here we can simply use our find product helper method where we pass the ID which is the product I would you were extracting here now of course find product returns a promise so we could add a van block or add async and then I'll wait this and now we have our product here now that's nice we got our product in in this case here now we want to update this product and now updating is really simple in Mongoose we can simply edit this product object here by overriding the data we want to override and then just saving it back to the database so we got our product here previously we copied that now there is no real need because this is a newly created object anyways it fetches the data from the database and creates a new object so no need to copy it instead I'll name it updated product remove this line here and now we're editing the updated product and now what I meant is that we just have to say updated product save at least normally we could here the problem is that find product in the end does not return the Mongoose object which is created here but our own object which adheres to our product description and that's not really what I want to have here because well this doesn't have a safe method and indeed it doesn't so to still use this helper method would all do here's all not return my own product here but allons that just returned the product which Mongoose fetched and created here because it will be that object that has all our data but that also has this mom whose magic behind the scenes so here we don't want to return a promise with with our product as we define it here just as interface but instead we kind of need to let typescript know that our product here has these properties but is actually based on the Mongoose model class so to say so on the base class every Mongoose model has and right now typescript doesn't notice but to let it know we can install one extra package here with npm install' - - safe def and that's the ad types mongoose package this ads type annotations for Mongoose and helps us with working with this Mongoose package with that added here on our interface we can add extend and extend Mongoose dot document now extends is a keyword you might know from classes in typescript you can also extend interfaces and this means that our interface here is based on this based interface your document is an interface provided by mongoose hence Mongoose dot document we're importing everything under this mongoose package up there and then we extend this mongoose document interface and we add our own properties to it and with this adjustment made in the product service we get rid of this save error because now it's clear to drive script that updated product is nian based on a constructor on this model which has our own data description title and price but which also has all these mongoose magic methods and properties and now for a get single product we need to make a slight adjustment to return proper data I'll do the conversion here and set this to product ID title to product title description to product description and prize to product price so now I'm converting that data here and get single product and an update product now find product returns as a mongoose model object in the end and now updated product which we get from find product which is our helper method is such an object created by mongoose therefore it wraps our data but it also has the Mongoose helper methods and therefore now we can call save and now Mongoose automatically tracks all the changes we did so for example that we maybe change the title or maybe changed the description or all of that and then when we call save again it won't enter a new document but since we're doing this on an existing one which already has an ID which was fetched from the database since we're doing this in an existing one it will update the existing one in the database and now a safe will automatically sent the right query to write that update to the database so if we save this let's quickly check if getting a single product still works yes it does and now let's use that ID here together with patch to update a product so here I want to update this product with a first test is the first product and the new data I send is an updated title and a new price so let's it send here and I get ok I forgot something of course update product returns a promise now because we're using async await hence in the controller we should also in update product either use then or add async here and then I'll wait this before we return anything but what if we returned null anyways so this is still a correct change to make so that we only send the response once this is done and not too early especially if this should crash we would otherwise send two responses which isn't a good idea but to see whether it worked let's go to the collection and let's refresh our database in our collection here and load documents again and what we see is that the title was updated and the price as well now let's see what happens if we try this on a document that does not exist we get a 404 error that makes sense and if I update a different product let's say this one a third test which still has a third test as a title in the database if we send an update there so for this ID and I changed description this is a brand new description and I sent this okay now let's reload our documents here and see whether that worked brand-new description so that worked we can of course also validated here by getting that single product and we see it here as well so this is all working the missing piece is removing a product there we call delete product in a service so let's go to the service to delete product here we find a product because we needed the index of the product to then remove it from our array now this will be done in a totally different way of course we'll still work with promises let's add a sync and let's now use our product model again and on that product model here we can now call delete one to delete one element and there we have to pass in a filter criteria which is a JavaScript object where you would define the key by what you want to fall through like the ID and then the value for that key in this case prod ID of course and this of course returns a promise promise at least if we call a X like behind it it works without that as well but the batter should also do that here on find by ID by the way and now we are waiting for this to be deleted then here we don't really have to return anything just one two well wait for this to finish in the end this should now delete a product where the idea is like product ID and in the products controller here under removed product we should now also add async and I'll wait this operation and then we can return now so let's get a single product like this one here that still works and now let's send a delete request for that ID like this so that looks good if I now go back and I try to get data for that single product that still works though and if i refresh here nothing was removed the reason for that oh yeah is ID now ID as I said is a getter we can use on that object mongoose crates for us to get the ID store in the database in the database is stored on underscore ID though so we should also use underscore ID here not ID because here we have to use the key as it's stored in the database so let's try it again with underscore ID in delete product send this request again and it works and if I now refetch this now we get not found which makes more sense because now if we update this here we shouldn't find the data here either now what you might have noticed is that before when we had the wrong criteria here we still weren't made aware of this right so that this succeded is not something we found out or we didn't find out that it failed actually so it would be nice of course to return a error if it fails for that let's get the result and console.log the result to get an idea of what we're getting back when this fails for example so here in the lead product I'm logging the result and now if I try to delete that same product which I just deleted which therefore isn't there anymore here we get a 200 response which doesn't make that much sense but in the response but in the result we're getting here we see we get a little bit of output and we find information about the operation which was done for example there we have a deleted count which is zero or generally n which is the number of affected documents which is zero and if on the other end I use an our document like this one which does exist and I delete this then you will see that in the log we have deleted count 1 and also N 1 so this is our indicator for whether something was deleted or not so here we can check if result n is greater than zero then we know it's exceeded or if it's equal to zero then we know it failed so here we could then throw a new exception then you will not found exception again because it probably felt because we didn't find a product so a wolf road is if we didn't find a so that we returned a correct error message if well we indeed failed to delete the product so let's save that and I'll rerun that query for that product which doesn't exist anymore and now we get 404 and now if I delete my last product which should still exist whoops and I use this as ID here we get 200 and if I try it again because now it was deleted we get 404 I now get all products we should get nothing because well there are no products anymore so that is how you can store or manage your data with the help of MongoDB it also means that in the product service we can of course get rid of that private products array which we now don't need anymore and I hope that it's clear how you now generally can work with MongoDB here with the help of Mongoose from inside of your nest Reyes application in general whatever you learn about MongoDB and Mongoose can be used in the same way here in SAS the most important difference to a normal node Express app is regarding how you set up your schema and more importantly your model with for a feature and that you can then simply inject your model and and work with it you could also work with Mongoose just as you know it from node Express manage everything manually instead of using injections on and that would all work but of course if you have the tools then this approach makes sure you stay more in the nest J's world and that is never a bad thing I hope this was helpful definitely share your thoughts and ideas in the comments I hope you like this video bye
Info
Channel: Academind
Views: 101,353
Rating: undefined out of 5
Keywords: nest, nestjs, nest.js, nest mongodb, nestjs mongodb, mongodb, mongo db, sql, nosql, tutorial, example, nest example, nestjs example
Id: ulfU5vY6I78
Channel Id: undefined
Length: 46min 21sec (2781 seconds)
Published: Thu Jul 04 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.