MERN API Controllers & Routers | MERN Stack Project

  Рет қаралды 26,076

Dave Gray

Dave Gray

Күн бұрын

Web Dev Roadmap for Beginners (Free!): bit.ly/DaveGrayWebDevRoadmap
MERN API Controllers & Routers are a necessary part of the backend logic in a MERN Stack Project. In this tutorial, we'll apply routing for CRUD ops to various HTTP methods and MERN controller methods.
💖 Support me on Patreon ➜ / davegray
⭐ Become a full-stack web dev with Zero To Mastery Courses:
- Advanced React & Redux: bit.ly/AdvReactDev
- The Complete Node.js Developer: bit.ly/CompleteNodeJS
- Jr to Senior Web Dev Roadmap: bit.ly/WebDevRoadmap-JrtoSr
🚩 Subscribe ➜ bit.ly/3nGHmNn
📬 Course Updates ➜ courses.davegray.codes/
🚀 Discord ➜ / discord
☕ Buy Me A Coffee ➜ www.buymeacoffee.com/davegray
👇 Follow Me On Social Media:
Github: github.com/gitdagray
Twitter: / yesdavidgray
LinkedIn: / davidagray
🔗 All Resources for this MERN Stack Project: github.com/gitdagray/mern_sta...
🔗 Playlist for this MERN Stack Project Series: bit.ly/3Sn4EaI
MERN API Controllers & Routers | MERN Stack Project
(00:00) Intro
(00:15) Welcome
(00:26) Starter Code
(01:05) Route user data requests
(03:42) Create the users controller
(09:34) Add controller methods to the user routes
(10:54) getAllUsers controller method
(13:05) createNewUser controller method
(19:25) updateUser controller method
(25:31) deleteUser controller method
(28:56) Install Postman
(29:29) Testing controller methods with Postman
(42:33) Student Challenge
📚 Suggested Pre-requisites for this MERN course:
🔗 Node.js for Beginners full course: • Node.js Full Course fo...
🔗 React JS for Beginners full course: • React JS Full Course f...
🔗 Redux Toolkit for Beginners full course: • React Redux Full Cours...
🔗 React Login Playlist: • React Login, Registrat...
📚 Tutorial References:
🔗 MongooseJS: mongoosejs.com/
🔗 express-async-handler: www.npmjs.com/package/express...
🔗 bcrypt: www.npmjs.com/package/bcrypt
Was this MERN Stack API Controllers & Routers tutorial helpful? If so, please share. Let me know your thoughts in the comments.
#mern #stack #api

Пікірлер: 207
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Part 4 of The MERN Stack Project Series - This video focuses on the routing and controllers that are necessary for the backend of our MERN Stack. We will route each HTTP CRUD request to a controller method that handles the logic for the requests. This tutorial is not for beginners. If you are a beginner, check out my full courses all in one playlist here: kzbin.info/aero/PL0Zuz27SZ-6M1Uopt6_VL3gf3cpMnwavm
@audraogilvy4781
@audraogilvy4781 4 ай бұрын
Your teaching style is the BEST. Thank you so much for taking the time and explaining things with a clear desire for us nameless, faceless students to comprehend.
@idontstudyforamidterm1069
@idontstudyforamidterm1069 8 ай бұрын
This is such a great video.. because of the choice of you and others to have such courses on youtube for everybody to access for free, people can get into one of the most important fields in our age without really paying much .. i literally benefit from this content way more than i do from uni professors in my country .. maybe bc uni here is bad but still, i see a lot of people in developed countries benefit from this as well .. like A LOT of them.. Mad respect for dave grey and net ninja and brocode and tim and all these cool people!!
@bikramchettri9405
@bikramchettri9405 Жыл бұрын
Love your content and teaching style.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Thank you for the kind words, Bikram! 💯
@gilogilala8475
@gilogilala8475 Жыл бұрын
am so loving this course 💯
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Glad to hear that! 🙏
@aeronwolfe7072
@aeronwolfe7072 Жыл бұрын
just finished chapter 4 with a working backend! thanks so much for your hard work Dave!
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
You're welcome!
@adarshalone7579
@adarshalone7579 Жыл бұрын
I am speechless bro.... Thank you so much for better explanation, keep going👍❤️
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
You're welcome, Adarsh! 💯
@servant-of-the-Praiseworthy
@servant-of-the-Praiseworthy Жыл бұрын
Dave!!! I know people say this a lot, but THANK YOU - you really are out here helping people who would primarily get confused or frustrated half way into these things😂😂
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
You're welcome! 💯
@therealdevopsintern
@therealdevopsintern Жыл бұрын
Wow, the errors on the backend controllers was well handled. Right from "no user found", to getting a "duplicate user" response e.t.c. An API was given to me from Sloovi firm to consume to my react front end app, while testing the API, I found out that at every point where I didn't supply the right information I always got a response error which was helpful - showing me where my problem was coming from. Now I know it's done. Many thanks Dave you are best, this section was well crushed. 🚀 🚀
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Thank you, Kelvin! 🙏💯
@erkinabdullaev7769
@erkinabdullaev7769 Жыл бұрын
I am enjoying learning from the course thank you !!!
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
You are welcome!
@sonamohialdin3376
@sonamohialdin3376 Жыл бұрын
Amazing tutorial with clear explanation thank you
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
You're welcome, Sona! 💯
@emmanueladuraibitoye9935
@emmanueladuraibitoye9935 Жыл бұрын
Thank you Dave. Your contents are rich.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Thank you, Emmanuel! 💯
@abdulrahmanagboolaosho3582
@abdulrahmanagboolaosho3582 Жыл бұрын
Dave I am so grateful to you, you have taught me nearly all I know, I went from not understanding meta-tags in html to writinga backend server, plus you answer all of my questions no matter how stupid they may seem, you truly are irreplacable, I am sure your channel will continue to grow 👍
@abdulrahmanagboolaosho3582
@abdulrahmanagboolaosho3582 Жыл бұрын
also could you please do a video using express with an sql db like postgres
@abdulrahmanagboolaosho3582
@abdulrahmanagboolaosho3582 Жыл бұрын
is it ok to use those mongoose method like findOneAndDelete, findByIdAndDelete e.t.c
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
You're welcome!
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Thank you for the request!
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Yes, it is ok.
@stellachieh
@stellachieh 10 ай бұрын
I want to give you more than one like! Thank you so much!!
@manutube8080
@manutube8080 Жыл бұрын
Thank you Dave! Really Thank you
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Welcome!
@marcohama1
@marcohama1 Жыл бұрын
Best tutorials series ever
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Thank you!
@thisurathenuka8362
@thisurathenuka8362 Жыл бұрын
Thank you for this amazing course Dave. I'm loving it. But one thing I didn't understand is why you didn't use resource identifiers in PATCH and DELETE requests ? I thought it was the best practice. I'm just asking for learning purposes. Thanks again, this has been the most pragmatic MERN course on KZbin.
@olepederg
@olepederg Жыл бұрын
Great work Dave! A small tip when checking for duplicate username during update is to do a case insensitive search. It can be done with a regex search and setting the option "i" for case insensitiv. Bevare to check the username and escape all characters that can be used for wildcard search and be a security risk. const duplicate = await User.findOne({ "username": { $regex: username, $options: 'i' } }).lean().exec(); Or we can make a case insensitive index of the for the username field in MongoDB.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Thank you! 🙏 This is a great idea and something I didn't think of. Adding this to my "refactor notes" before the series is over. 🚀
@TribalWolvesNetwork
@TribalWolvesNetwork Жыл бұрын
Or you can just set unique to true in the user schema, to avoid any duplicates?
@olepederg
@olepederg Жыл бұрын
@@TribalWolvesNetwork You could still have both «dave» and «Dave» as unique entries. I would probably just enforce lowercase on input and on login.
@MrDFJohnson
@MrDFJohnson Жыл бұрын
Thank You Dave !!!
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
You're welcome!
@kingsleyobi-ko9zj
@kingsleyobi-ko9zj 4 ай бұрын
sir dave you are the best
@jiweihe3413
@jiweihe3413 Жыл бұрын
Thanks! This series is really helpful. I will follow till the end. Do you happen to have any video that teaches graphql?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
You're welcome! Thank you for the request! I do not currently have a GraphQL video, but I'd like to make one. 🚀
@zidanbadr1658
@zidanbadr1658 Жыл бұрын
Please could you tell us which software architecture you follow to build this project. I faced this question during interviews, and nobody cover this topic while they build their project, KZbin is full of these examples but no one mention which pattern he used to accomplish his project. Love your content btw.
@raymondterry2346
@raymondterry2346 Жыл бұрын
I would like to know as well.
@ngirababyeyieric3730
@ngirababyeyieric3730 Жыл бұрын
Me too i would like to know
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Great question! 💯 For the backend REST API built in these first 4 tutorials, you could say I used the Model-View-Controller pattern although we are not focused on the View aspect, we did create a default index.html and 404 page. I do discuss this a bit more in my Node.js course that is suggested as a pre-requisite. The frontend begins in the next tutorial, and it will follow a standard React and React Router pattern with the file management following the same pattern I used in my Redux course and used in the Redux docs which organizes files by feature. 🚀
@zidanbadr1658
@zidanbadr1658 Жыл бұрын
@@DaveGrayTeachesCode thank you sir for your reply. I still Just confused about the part of the "view". It's common when we build a full stack app that we create 2 repositories, one for frontend and the other for backend, in this case, is it possible to consider the frontend repository our "View" if we talk about the MVC pattern? And I have another question related to software architecture. Is each repository has an architecture, like the frontend follow the SPA or SSR, and the backend follow the monolith or microservices architecture. I am sorry if I did not explain well, but we need to know what we are doing when building our projects, because these technical stuff are wide and I just suggest you about these topics in order to improve your content to be different from other KZbinrs. And thank you again, I appreciate your hard work
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
@@zidanbadr1658 yes, each repository has its own architecture. In this project, the backend can be considered MVC. The frontend is a React SPA with React Router.
@omarakki705
@omarakki705 Жыл бұрын
Thanks dave
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
You're welcome, Omar! 🙏
@TravinskiyVladislav
@TravinskiyVladislav Жыл бұрын
That's course all what i need
@seightan
@seightan Жыл бұрын
great video as always! your voice is very soothing. question: what’s the reasoning for segregating the api and client in different repos? is it mostly for scalability? or something else?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Thank you! 🙏 Unless a solo project, the frontend and the backend are likely built by different teams and possibly hosted in different places. Backend is running Node.js and the frontend will be a React build. Separate deployments would be set up for each.
@saketparasher3762
@saketparasher3762 Жыл бұрын
Hi Dave, thanks a lot for this most awaited series. I have one request, are you going to use RTK Query in front end for api calls, authentication and authorization. That will be awesome as we will get hands on practice for redux-toolkit and rtk query in real world project
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
That's the plan! Redux with RTK Query for state management and the API layer. 🚀
@saketparasher3762
@saketparasher3762 Жыл бұрын
@@DaveGrayTeachesCode thank Dave, I guess then you will also include auto refetch of access tokens using refresh tokens, and auto login. It will help us a lot in understanding RTK query completely
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
@@saketparasher3762 this is correct!
@saketparasher3762
@saketparasher3762 Жыл бұрын
@@DaveGrayTeachesCode Awesome thanks a lot ❤🙏
@xyz_only_10x
@xyz_only_10x Жыл бұрын
awesome video
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Thanks!
@abmestri25
@abmestri25 Жыл бұрын
Love from India ❤
@eurogamestyle5761
@eurogamestyle5761 Жыл бұрын
Hi Dave Instead of making a findOne call for checking duplicates I have mentioned that this field in unique in model
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Yes, see another comment here as well where it is discussed and may not be a case-sensitive solution... in addition, several other options are listed.
@markpiland5256
@markpiland5256 Жыл бұрын
I came to this page because I had just finished a full stack bootcamp and was attempting to build my own React app. While working on the authentication piece, I got very lost in trying to solve how to stop React from calling my fetch twice due to the StrictMode which I preferred not to turn off. The double fetch was messing with my tokens and so I my google search brought me here. I started the authentication video and was so impressed, I decided to watch the full course and follow along from the beginning. My only question here is: I know we built our own routers and what not, but why use bcrypt instead of using something like passport-local-mongoose which handles the salting and hashing? I'm not saying I prefer either as I don't have the experience to say. I'm genuinely curious as to which is preferred? I'm leaning towards your method as it's teaching me more.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Thanks! Yes, totally preference - or just using the package you are familiar with.
@hosamgnaba3205
@hosamgnaba3205 Жыл бұрын
Hi dave, awesome video, but i just wonder why didn't use the joi library for validation ... thanks
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
At some point, I have to stop adding things - but that does not mean you cannot make modifications to your preferences. If there is a library / dependency you want to use, go for it!
@TravinskiyVladislav
@TravinskiyVladislav Жыл бұрын
Thank you
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Welcome!
@witelfortgelin5377
@witelfortgelin5377 Жыл бұрын
Hello sir! Firstly I can say you thanks for this project, it is exactly like a project I have to do. So, how manager can assign employee to specific admin? Where it's only the admin for which manager assign user who will can see the activity of the assigned user.
@jhkamikaze010902
@jhkamikaze010902 Жыл бұрын
Dave, I was working on the notes controller, and I was wondering if it would be a good idea to add a check for whether the user a note is assigned to exists. I tried to do this with a User.findById but it kept returning a casting error, so I hope that you can maybe implement it in the next episode!
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Not a bad idea, Jerome. I took the opposite approach of not allowing a user to be deleted if notes were still assigned to that user. For a note to be created, a user must also be assigned. With those checks in place, I didn't think I needed to add that extra check, but it is good practice! Look at my usersController and apply logic that is similar to my check for notes before the user can be deleted.
@ikpashteen6950
@ikpashteen6950 Жыл бұрын
Hey Dave You'r doing such a wonderful job for us. In lecture 2 in Config file corsOption you used ternary operator for staus. Please specify there's some confusion.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Thank you! I'm not sure how to explain it differently than I did? Do you understand ternary operators? If not, here's a tutorial on those: kzbin.info/www/bejne/n5ObfnuJgtynj8k
@ikpashteen6950
@ikpashteen6950 Жыл бұрын
Yes Sir, I know what is Ternary operator. BTW thank you very much for your time.
@CTILET
@CTILET Жыл бұрын
Oo good for portfolio
@JesseTrammell
@JesseTrammell 11 ай бұрын
Hank knows a lot about propane and propane accessories, but he doesn't know a lot about creating strong passwords. Dave, however, your series on MERN and REACT have both been very good. Both series are done well enough to be behind a pay wall and still be worth.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 11 ай бұрын
Thank you! 😆
@wrightholding2768
@wrightholding2768 Жыл бұрын
In the model, you set a default "employee" value for roles. To create a valid user, you wouldn't need to first validate inclusion of the roles array in json
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Hi Robert, if you watched the video you might have missed where I discussed this? While you are correct, the decision was intentional.
@MuhammadArif-op1cn
@MuhammadArif-op1cn Жыл бұрын
Please, do implement axios interceptor for error handling in one place for all these status code in the client side.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
That could be a good approach. I'll be using RTK Query with the fetchBaseQuery instead of Axios, but it will be an efficient approach.
@regilearn2138
@regilearn2138 Жыл бұрын
Hi Dave,I have learn lot from your channel. Last time according to your reply ,about data persist during refresh.so imagine if we use "RTK query",do we still need to use redux-persist(another lib) for this or can we manage this with only using RTK QUERY ,and ,i would like to request pls teach us how to persist data on refresh and how to do multistep form in real-world example. Appreciate it Dave ❤❤❤❤
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Hi Regi - in this MERN Stack tutorial series, we will persist Redux data without using the redux-persist library or any other library other than RTK Query with Redux. This is coming up in the next few lessons! 🚀
@regilearn2138
@regilearn2138 Жыл бұрын
@@DaveGrayTeachesCode Thank you ❤
@rosadoaraujoemilio9549
@rosadoaraujoemilio9549 2 ай бұрын
Hi Dave! I have a problem, when i use postman to do the get or post method postman only returns the 404.html instead of the empty array or the JSON message idk why but im stucked. Great videos tho and greetings from México:)
@philonouz
@philonouz Жыл бұрын
thanks Dave, but at 12:40, why the status code shoud be 400? Why not an ok response with an empty array as the result?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Good question! This could be your preference to do so. The frontend app will display error messages, so instead of adding extra logic in the frontend to check for an empty array and provide a useful message, I decided to let the error handling that is already in place display the useful message in the frontend. It can be considered a "bad request" aka 400 if the data does not exist when requested. It comes down to preference on this one.
@philonouz
@philonouz Жыл бұрын
@@DaveGrayTeachesCode Oh I see. Thanks for the reply :))
@eyriusbacterius
@eyriusbacterius Жыл бұрын
First of all thank you for the MERN series but i got one question: Wouldn’t it be easier if we just set in the schema the username etc. to unique?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Good question, and you can do that, but there is some discussion of this in other comments as well. The result will not be case-sensitive. Another good solution is posted in the discussions.
@eyriusbacterius
@eyriusbacterius Жыл бұрын
@@DaveGrayTeachesCode oh okay I did not know that. Thank you for the quick response :)
@timnesterov1156
@timnesterov1156 11 ай бұрын
I noticed when testing the update user endpoint around 37:30, if instead of changing the 9 to a 1, you simply remove the 9, the async handler takes over and you get an error saying "Cast to ObjectId failed for value ...". I fixed it by putting any code that fetches the user from the DB by id in a try/catch block, but there may be a better solution.
@chrisstucker1813
@chrisstucker1813 8 ай бұрын
Yes because its not a valid mongo ID once you remove a character. There's a mongoose function called isValid(id) which lets you check if its a valid ID or not
@colcv3360
@colcv3360 Жыл бұрын
My 2 cents: If you are using await with any mongoose operation (find, findOne, etc.), you don't need to use .exec() after the find method. Mongoose will automatically execute the query for you.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Your 2 cents are very welcome. I try to stick with the documentation which says exec() is needed: mongoosejs.com/docs/promises.html
@simonedwards7101
@simonedwards7101 Жыл бұрын
Hi Dave, in the notesController > getAllNotes > notesWithUser... Why do we return the username with the notes if the username is already in the note? Is it that we're just doing it on the server rather than having to extract it on the client side later? Or something else? I hope that makes sense :-)
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
I understand your question, but usernames are not stored in the notes. Notes contain a user id which we then reference to get a username from the user records. In the note model, I did name this field "user" instead of "userId" which might add to that confusion. 💯
@simonedwards7101
@simonedwards7101 Жыл бұрын
@@DaveGrayTeachesCode Thanks Dave, that makes sense now and agreed it did throw me as I also didn't implement the code :-) All good and thanks for taking the time to explain.
@simonedwards7101
@simonedwards7101 Жыл бұрын
And if I'd paid closer attention to the type for the user field in the notes model that would have answered my question.. Head in hands moment... Thank you for your patience Dave :-)
@sterkriger2572
@sterkriger2572 Жыл бұрын
Hi Dave at the point where I test if I can patch it always return "message": "All fields except password are required" regardless of what I send with PATCH
@twitch-clipz
@twitch-clipz Жыл бұрын
I am having the same problem. I think I found the problem, remove the "_" underscore from the JSON body that is infront of "id". Let me know if this works
@sarahimpextradingenterpris6286
@sarahimpextradingenterpris6286 11 ай бұрын
I also get same response
@Grishopping
@Grishopping Жыл бұрын
Greetings DAVE thank you very much for sharing your knowledge... (excuse my bad ENGLISH I use a translator) I tell you that instead of POSTMAN , I use REST Client a VSCODE PLUGIN..... Jose Grillo greets you reporting from Venezuela hahahaha Saludos DAVE muchas gracias por compartir tus conocimientos... (disculpen mi mal INGLES uso traductor) te comento que en vez de POSTMAN yo uso REST Client un PLUGIN de VSCODE
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
You're welcome! And hello to Venezuela! 👋
@ashharkausar413
@ashharkausar413 Жыл бұрын
Dave what are your thoughts on MongoDB as a database? I wanna test in my own projects but I've heard bad things about it. Would love to know.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
I like it. It is easy to set up quickly. It scales well-enough for some large companies to be their customers, too: www.mongodb.com/who-uses-mongodb
@ashharkausar413
@ashharkausar413 Жыл бұрын
@@DaveGrayTeachesCode ty
@mrbilchalan
@mrbilchalan Жыл бұрын
What if you used "unique: true" for username in user model then send a error message back. For updating the user, is there needed to check duplicate logic then. Apology for my poor english and thank you.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
This could also work. As you have discovered, there is usually more than one way to achieve the same goal. Try coding it out. It should generate an error when you try to save. You will need to grab that specific error and send a message back in response to it.
@stevereid636
@stevereid636 Жыл бұрын
Is the @desc @route @access at the top of each handler purely serving as a visual explanation?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Yes, it is the standard way to note the details. 💯
@AldisSv
@AldisSv Жыл бұрын
Dont we need to add also .status(200) for updateUser controller at the end? I see that only .json() is returned.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Status 200 is the default so you can specify it, but you don't need to. You can check the response status to verify with Postman.
@stonecomstock
@stonecomstock Жыл бұрын
Hi Dave. How come your ID field key's don't have an underscore before them like this _id? Mine do, and it's breaking my code in a few spots as I am trying to reference the id from req.body instead of _id. I figured out the error and was able to fix it, but wondering why its different than yours? According to the documentation it's supposed to have the underscore, so I am curious why yours doesn't.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
The request (req) is sent from the user in the frontend. If you are testing with Postman for example, you would be sending the id. Yes, MongoDB uses "_id", but when you findById, you can just pass in the id received from the request. Your backend code here will send the "_id" field to the frontend. In lesson 6, we transform the response and change it back to simply "id" in the frontend.
@stonecomstock
@stonecomstock Жыл бұрын
@@DaveGrayTeachesCode Thank you so much for the reply! Makes a lot of sense. I am loving all of your tutorials :)
@CodeandVibe
@CodeandVibe Жыл бұрын
Does anyone else get a status 200 saying "duplicate is not defined" when trying to create a new user? my code looks right but not sure what Im doing wrong
@blackaccel
@blackaccel 10 ай бұрын
Can someone explain to me why: duplicate?._id.toString() !== id, I mean if it finds the duplicateUser isn't it enought to send back the json error message?
@kengirard9726
@kengirard9726 8 ай бұрын
When trying to create a new note in Postman, and you get the message: ValidationError: Note validation failed: user: Cast to ObjectId failed for value "Hank" (type string) at path "user" because of "BSONError" it is because you need to use the user's id, so it should be something like: "user": "6510ba26cb36582a1d76da79" If you are using the user's id, and Postman just hangs: It is because mongoose-sequence is no longer supported, and doesn't work with mongoose 7+. Replace mongoose 7+ with mongoose 6.12.0 by entering "npm install mongoose@6.12.0" Then make sure that your package.json & package-lock.json say "mongoose": "^6.12.0"
@altiansyahfanny3720
@altiansyahfanny3720 Жыл бұрын
Hello dave, I got this msg "Cast to ObjectId failed for value \"62f5bcf44e436e72e8242f0\" (type string) at path \"_id\" for model \"User\" when I input wrong id in patch method. what I missed?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
You can compare your code to the source code I provide in the course resources. It could be an error that you are receiving from the error handler - did you check the error log the server is creating?
@DeTodoUnPoco-ny8tx
@DeTodoUnPoco-ny8tx Жыл бұрын
Hi guys, I've got this error when I tried to implement the notesController : Counter already defined for field "ticketNums". Can someone help me with it? Many thanks. Great tutorial by the way!
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Please compare your code to my source code available at the course resources link in the description. It is available for each chapter. Sounds like there is a difference somewhere.
@ramziosta
@ramziosta Жыл бұрын
I downloaded the files and Im getting this error when creating a new note. { "message": "Note validation failed: user: Cast to ObjectId failed for value \"mojo\" (type string) at path \"user\" because of \"BSONTypeError\"" }
@kingsleyobi-ko9zj
@kingsleyobi-ko9zj 4 ай бұрын
it should be like this "user": "659ae01f604e48da54e75480" and not in alphabets
@TyrionLannister-zz7qb
@TyrionLannister-zz7qb Жыл бұрын
while creating the userController, the ufnctions user.save() and user.deleteOne() are showing undefined, along with that after testing in postman, i am recieving error message as 'user.save()' is not a function
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Sounds like you have a difference in your code. Go back over the code available in the course resources. If you find it difficult to see the differences, use a tool like this: www.diffchecker.com/text-compare/
@TyrionLannister-zz7qb
@TyrionLannister-zz7qb Жыл бұрын
@@DaveGrayTeachesCode thank you, i checked, seems like .save() method has been deprecated by mongoose, .findByIdAndUpdateOne() worked well for me. deleteOne is working fine. Although while checking notes controller and notes schema, there is some issue with AutoIncreament, as postman request is not processed, it is kept hanging without response / error etc. I used controller and model given at github. If AutoIncreament part is commented, the code works fine
@neatunet
@neatunet Жыл бұрын
Hi Dave, thank you for this amazing series. I have a question: I created a notesController (then I matched it to your code so that they are the same). However, when I test the /notes route with Postman, there is an error in the POST request. When I send the following JSON (content-type: application/json): { "user": "64025243cba56357618707b5", "title": "My new note", "text": "Do something..." } The server doesn't return anything, just the loading animation in Postman. I think this is because of the user field. Do I send it correctly? If I'm not mistaken, the user field in the Note model should have the id of the user the note is assigned to. And I have the user with that id in the database, but the note is not being created. Can you please tell me what is my mistake?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
You can check the course resources file and use this tool to insure your code is the same: www.diffchecker.com/text-compare/ Also verify the data you are sending matches the Model data that is expected. I show how I do everything, so if you missed something the first time through it might be worth going back to review. Keep going!
@neatunet
@neatunet Жыл бұрын
@@DaveGrayTeachesCode Thank you for answering. I checked and everything is the same. However, it seems that the problem is because of the AutoIncrement plugin from the mongoose-sequence package. When I remove it, everything works fine. I have the same plugin code as yours: noteSchema.plugin(AutoIncrement, { id: 'ticketNums', inc_field: 'ticket', start_seq: 500, }); I thought maybe they released a new version with breaking changes, but I checked the docs and they look normal
@phuongvan6105
@phuongvan6105 Жыл бұрын
@@DaveGrayTeachesCode Hi Dave, I met the same case. The reason came from this plugin, when I disable it, it can create a new note. but if not, it does not return anything when created by postman. Hope you advise. Thanks noteSchema.plugin(AutoIncrement, { inc_field: 'ticket', id: 'ticketNums', start_seq: 500 })
@TravinskiyVladislav
@TravinskiyVladislav Жыл бұрын
I had a similar problem due to the fact that I was using modules, but common js works fine Decided to write my solution:
@rjmacalino3186
@rjmacalino3186 Жыл бұрын
i'm also stuck in this error.
@surajnaik6937
@surajnaik6937 Жыл бұрын
Hi Dave. I was testing the code and I have an issue. While sending data from postman to create a user , for the roles property, In the code , I am getting reference error.:Arrays is not defined. The Arrays.isArray() is throwing the error. Can you give me hint of what migght be the issue?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
It should be Array.isArray() ..not "s" at the end. You can reference my code in the course resources, too.
@surajnaik6937
@surajnaik6937 Жыл бұрын
@@DaveGrayTeachesCode Yeah,. That was the issue. Thank you very much.🤩
@himalayapal9482
@himalayapal9482 Жыл бұрын
the mongoose sequence plugin is not supporting in mongoose v7 so use mongoose v6.11.0 . If you know the solution in v7 help me.
@swartex92
@swartex92 Жыл бұрын
what theme do you have installed in the editor?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Github theme - I think linked in description and course resources 🚀
@swartex92
@swartex92 Жыл бұрын
@@DaveGrayTeachesCode thanks! 👍
@winningless
@winningless Жыл бұрын
Is `.select("-password")` still required. Mongo seems to not return it by default now.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
I'm fairly sure that it is. To test for yourself, just remove it. You should receive all user data including the password.
@FariKomeiji
@FariKomeiji 11 ай бұрын
hi! how can i make it so i can have more than one post method in my userRoutes and controller? i want it so i can also get one user by id
@DaveGrayTeachesCode
@DaveGrayTeachesCode 11 ай бұрын
If you are getting something, it sounds like a GET route? You can set up as many different routes as you want.
@FariKomeiji
@FariKomeiji 11 ай бұрын
yes but im not sure how to add them in: router.route('/') .get(usersController.getAllUsers) .post(usersController.createNewUser) .patch(usersController.updateUser) .delete(usersController.deleteUser) im too confused how the userRouter works
@FariKomeiji
@FariKomeiji 11 ай бұрын
NEVERMIND i just found out from your other tutorials multiple controllers and routes can work with the same models, thanks!
@rjmacalino3186
@rjmacalino3186 Жыл бұрын
Thank you, dave! I managed to do the notes (student-challenge) but i did a lot of debugging and the biggest one is the mongoose-sequence. mongoose-sequence is not supported anymore, i found another package named '@alec016/mongoose-autoincrement' and i don't know how long it will work tho. Debugging my code helped me to understand your code and basically what is happening with all the MVC and Mongodb connection overall. I am planning to use this server for my front-end which will be just a vanilla js for now and refactor it to react later.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
If you want to use mongoose-sequence, you could install the same versions of dependencies that I have in my package.json file by copying my package.json file from the course resources and then using: npm install It is good to learn how to fix things as they progress as well.
@rabitenaziriperyserdi7278
@rabitenaziriperyserdi7278 Жыл бұрын
Hello sir. I know basics of html, css and javascript. What should i learn next?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Great question! You have built a good foundation. At this point, you can decide. You can begin to learn backend web development with Node.js OR you can go further with frontend web development by learning a library like React.js. I eventually recommend doing both, but it is your choice where you want to begin. 💯🚀
@RishitaBose
@RishitaBose Жыл бұрын
Can somebody help me with this error I'm getting while using postman and browser as I enter localhost:3500/users {"message":"user is not allowed to do action [find] on [test.users]"}.
@west-la-coding
@west-la-coding Жыл бұрын
This is a Mongo DB issue, have to go set the role to be able to Read/Write
@palakmantri7547
@palakmantri7547 Жыл бұрын
@DaveGrayTeachesCode how can we create notes database in mongodb?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
That happened in lesson 3. This is lesson 4. Full playlist: kzbin.info/aero/PL0Zuz27SZ-6P4dQUsoDatjEGpmBpcOW8V
@johncena-qr4yg
@johncena-qr4yg Жыл бұрын
how do i make POST request for create notes. which require user:{ type: mongoose.Schema.Types.ObjectId,}
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Create a user first. Make a request for the users. Get the _id property from the user you want to create a note. When you create the note, provide that _id value for the user field.
@vijendrashekhawat9427
@vijendrashekhawat9427 7 ай бұрын
Hello Dave, facing one problem, when i try to save note ( which has reference of user) , request is never fulfilled. it just got stuck here : const note = await Note.create({ user, title, text }) any help please
@DaveGrayTeachesCode
@DaveGrayTeachesCode 7 ай бұрын
Comments on my Discord on this and maybe in these comments, too - the mongoose sequence dependency does not work with the latest version of Mongoose. You can rollback to the version of Mongoose I use in my provided source code OR you can find another package providing what mongoose sequence does. There are several.
@vijendrashekhawat9427
@vijendrashekhawat9427 7 ай бұрын
@@DaveGrayTeachesCode Thank you very much. Yes, i found that this issue is related to mongoose-sequence.
@ajayshekhawat2292
@ajayshekhawat2292 Жыл бұрын
PLEASE HELP i am not been able to conect to local host , its just loading and its showing request pending in networks everything is working fne there is no error , its also logging the get request but the browser is just keep loading and nothing on hte page
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
At this point of the project, you are only building the backend REST API. The only thing that should show in the browser is the index.html page. You can use the course resources link in the description to compare your code to mine and see what is different.
@bahaeddine4278
@bahaeddine4278 Жыл бұрын
kept getting this error "message": "All fields except password are required" even when I cloned the repo from github ?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Sounds like you are routing to the update path of the user. You can see that response message and what causes it in the user controller.
@inspirationalquotes5840
@inspirationalquotes5840 Жыл бұрын
could someone send the JSON body to create a note, I'm getting an error.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Are you attempting to send the raw json with Postman to test the route and controller? If you look at the provided source code in the course resources for this lesson, you will see I am looking for a request body object that contains user, title, and text properties. The user property is the user ID. Create a user first. Get the id for the user by requesting the user data. Now create the note with that id as the user value. Both title and text should be string values.
@inspirationalquotes5840
@inspirationalquotes5840 Жыл бұрын
@@DaveGrayTeachesCode Hi Dave, thanks for helping me, this is the user { "_id": "62f734ef9fa6f693ac1719bb", "username": "Osman", "roles": [ "Employee" ], "active": true, "__v": 0 }
@inspirationalquotes5840
@inspirationalquotes5840 Жыл бұрын
@@DaveGrayTeachesCode and this the json for creating a note { "user": "62f734ef9fa6f693ac1719bb", "title": "Test", "text": "Test" }
@inspirationalquotes5840
@inspirationalquotes5840 Жыл бұрын
@@DaveGrayTeachesCode and i'm getting this message The resource you have requested does not exist.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
@@inspirationalquotes5840 that looks like a message you would get from MongoDB if you are looking for a record that does not exist. Just guessing here. There must be a difference in your code when compared to mine.
@azzamuddin9484
@azzamuddin9484 9 ай бұрын
Hey dave! such a great tutorial explained very well. I have implemented the notes controller and model the same way as you did but on Postman on post request, it get stuck and not creating the note. const Note = require('../models/Note') const User = require('../models/User') const asyncHandler = require('express-async-handler') const getAllNotes = asyncHandler( async(req, res) => { const notes = await Note.find().lean() if(!notes){ return res.status(400).json({message: 'No notes found'}) } const notesWithUser = await Promise.all(notes.map(async (note) =>{ const user = await User.findById(note.user).lean().exec() return {...note, username: user.username} })) res.json(notesWithUser) }) const createNewNote = asyncHandler(async (req, res) => { const {user, title, text} = req.body if(!user || !title || !text){ return res.status(400).json({message: 'All fields are required'}) } const duplicate = await Note.findOne({title}).lean().exec() if(duplicate){ return res.status(409).json({message: 'Duplicate note title'}) } const noteObj = {user, title, text}; const note = await Note.create(noteObj) if(note){ return res.status(201).json({message: 'New note created'}) }else{ return res.status(400).json({message: 'Invalid note data received'}) } }) const updateNote = asyncHandler(async(req, res) => { const {id, user, title, text, completed} = req.body if(!id || !user || !title || !text || !completed){ return res.status(400).json({message: 'All fields are required'}) } const note = await Note.findById(id).exec() if(!note){ return res.status(400).json({message: 'Note not found' }) } const duplicate = await Note.findOne({title}).lean().exec() if(duplicate && duplicate?._id.toString != id){ return res.status(409).json({message: 'Duplicate note title'}) } note.user = user note.title = title note.text = text note.completed = completed const updatedNote = await note.save() res.json(`${updatedNote.title} updated`) }) const deleteNote = asyncHandler(async(req, res) => { const {id} = req.body if(!id){ return res.status(400).json({message: 'Note not found'}) } const note = await Note.findById(id) if (!note) { return res.status(400).json({ message: 'Note not found' }) } const result = await note.deleteOne() const reply = `Note ${result.title} with ID ${result.id} deleted` res.json(reply) }) module.exports = { getAllNotes, createNewNote, updateNote, deleteNote }
@DaveGrayTeachesCode
@DaveGrayTeachesCode 9 ай бұрын
The mongoose-sequence package is not compatible with the current version of Mongoose. Install the version of mongoose listed in my package.json. Other comments in here with more details on this, too.
@azzamuddin9484
@azzamuddin9484 9 ай бұрын
@@DaveGrayTeachesCode Fixed thanks a lot.
@kengirard9726
@kengirard9726 8 ай бұрын
For people having the same issue: If you are trying to create a new note and Postman just hangs: It is because mongoose-sequence is no longer supported, and doesn't work with mongoose 7+. Replace mongoose 7+ with mongoose 6.12.0 by entering "npm install mongoose@6.12.0" Then make sure that your package.json & package-lock.json say "mongoose": "^6.12.0"
@kingsleyobi-ko9zj
@kingsleyobi-ko9zj 4 ай бұрын
God will continue to bless you and sir dave..dude has really made me happy@@kengirard9726 @DaveGrayTeachesCode
@kingsleyobi-ko9zj
@kingsleyobi-ko9zj 4 ай бұрын
not all heroes wear capes bro@@kengirard9726
@AuxiliaryOfficial
@AuxiliaryOfficial Жыл бұрын
please make a tutorial how to integrate swagger on this pls
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
No need to make the same request on multiple videos. Responded to one of your other posts on this topic.
@alexchang8180
@alexchang8180 Жыл бұрын
First of all, thanks for the materials. I would like to ask if anyone here encounter this error => D:\Learning\mern\jwt_accesstoken ode_modules\mongoose-sequence\lib\sequence.js:196 if (connection.modelNames().indexOf(modelName) >= 0) { ^ TypeError: connection.modelNames is not a function The error seems to origin from the models/Note.js code line below noteSchema.plugin(AutoIncrement, { inc_field: 'ticket', id: 'ticketNums', start_seq: 500 }) Anyone know a fix to this? Much appreciated thanks!
@alexchang8180
@alexchang8180 Жыл бұрын
Found the issue: const AutoIncrement = require('mongoose-sequence')(mongoose). I added "" to mongoose. Hence the error.
@bikramchettri9405
@bikramchettri9405 Жыл бұрын
If we send "roles": [""] like this the user is created with empty roles
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
I guess the question is why would we send the roles like that? We can set our React app to avoid that. That said, if you want to check the elements in the array to confirm they are not empty strings, you can. You are correct that [""] will have a length of 1.
@mariusguissou4282
@mariusguissou4282 Жыл бұрын
👍👍👍👍👍👍👍👍👍
@stephenoluwaseun5907
@stephenoluwaseun5907 Жыл бұрын
Great tutorial Dave. Mongoose exposes us to a findOneAndUpdate() method. I believe it's an alternative to the save() method for updating fields in the user model.
@stephenoluwaseun5907
@stephenoluwaseun5907 Жыл бұрын
And also a findOneAndDelete() method passing in the _id, since there can't be duplicate id's or even emails in this case.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
You are correct, Stephen! Please feel free to refactor this code if you prefer to use that method. 💯
@pstha4537
@pstha4537 8 ай бұрын
can u create a complete Social media using MERN stack? and a Blog?
@Pareshbpatel
@Pareshbpatel Жыл бұрын
Very comprehensive tutorial on MERN Routers and Controllers. Thanks, Dave {2023-02-07}, {2023-02-13}
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
You are welcome!
@playingtheangel4413
@playingtheangel4413 Жыл бұрын
Hi Dave. I have a problem. When I want create new Note and send request - the server doesn't return anything, just the loading animation in Postman. But when I commenting this code : noteSchema.plugin(AutoIncrement, { inc_field: "ticket", id: "ticketNums", start_seq: 500, }); Then request is sending.What is my mistake?
@playingtheangel4413
@playingtheangel4413 Жыл бұрын
I solved it using mongoose-plugin-autoinc instead mongoose-sequence
@mmhef
@mmhef Жыл бұрын
@@playingtheangel4413 I was having this same issue and just created a manual counter in the code based on array length. I'll be able to revert back now - thanks!
@markpiland5256
@markpiland5256 Жыл бұрын
Thank you for your solution! Turns out, mongoose-sequence was abandoned by the author and the deprecated callbacks from inside mongoose cause this plugin to just hang. Mongoose-plugin-autoinc works perfectly!
@heguer87
@heguer87 11 ай бұрын
Hey Dave , thanks a lot! I pretty much finish your next js series. and after watching your content I decided to go and give a try to node js again, like I tried to learn it before but I would always get stuck for whatever reason. With your master explanations life is good man. I cant thank you enough. I hope I can get a job after the summer, I am 43 years old, hopefully not too old lol. By the way I wanted to mention that I added an extra line of code to check the roles. like they must be either of the 3 roles not a different role. Im guessing we will be selecting from front end, but someone could place a different role, right? const validRoles = ['Admin', 'Employee', 'Manager'] if (!roles.some((role) => validRoles.includes(role))) { return res .status(400) .json({ message: 'Role must be Employee, Admin, or Manager' }) }
@dror-krief
@dror-krief Жыл бұрын
I love you Dave! thank you so much you gave me value more then 12 month Full-stack course i took I really appreciate it 🫂
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Great to hear! 💯
React.js App Project | MERN Stack Tutorial
35:12
Dave Gray
Рет қаралды 22 М.
Middleware in a MERN Stack Project | REST API Tutorial
28:30
Dave Gray
Рет қаралды 28 М.
Ну Лилит))) прода в онк: завидные котики
00:51
狼来了的故事你们听过吗?#天使 #小丑 #超人不会飞
00:42
超人不会飞
Рет қаралды 59 МЛН
Dynamic #gadgets for math genius! #maths
00:29
FLIP FLOP Hacks
Рет қаралды 18 МЛН
어른의 힘으로만 할 수 있는 버블티 마시는법
00:15
진영민yeongmin
Рет қаралды 9 МЛН
How To Call a REST API In Java - Simple Tutorial
29:14
Coding with John
Рет қаралды 252 М.
How To Make a Django REST API - Full Tutorial & Deployment
40:18
Tech With Tim
Рет қаралды 47 М.
Angular Crash Course
2:01:32
Traversy Media
Рет қаралды 1,4 МЛН
Ну Лилит))) прода в онк: завидные котики
00:51