MongoDB Async CRUD Operations | Mongoose Async Await | Node.js Tutorial

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

Dave Gray

Dave Gray

Күн бұрын

Web Dev Roadmap for Beginners (Free!): bit.ly/DaveGrayWebDevRoadmap
Learn how to apply MongoDB async CRUD operations with async await and Mongoose in this Node.js Tutorial. This tutorial is the final lesson in the Node.js for Beginners tutorial series. You will also learn how to quickly deploy the REST API we have created with Node.js, Express, and MongoDB.
🚩 Subscribe ➜ bit.ly/3nGHmNn
🚀 This tutorial is part of a Node.js & Express for Beginners tutorial series playlist:
• Node.js Tutorials for ...
🔗 Starter Source Code: github.com/gitdagray/mongodb_...
🔗 Completed Source Code: github.com/gitdagray/mongo_as...
MongoDB Async CRUD Operations | Mongoose Async Await | Node.js Tutorial
(00:00) Intro
(00:05) Welcome and Overview
(00:51) refresh token controller
(03:33) logout controller
(05:54) auth controller
(07:45) testing the updated routes
(13:10) get all employees
(15:00) create a new employee
(17:20) update an employee
(20:46) delete an employee
(22:44) get a single employee
(24:10) test updated employee routes
(29:01) user admin routes
(29:56) deploy the REST API
🌱 MongoDB and Mongoose References:
MongoDB: www.mongodb.com/
Mongoose: mongoosejs.com/
📚 JWT References:
Intro to JSON Web Tokens: jwt.io/introduction
All You Need to Know About Storing JWT in the Frontend: dev.to/cotter/localstorage-vs...
NPM jsonwebtoken package: www.npmjs.com/package/jsonweb...
NPM cookie-parser package: www.npmjs.com/package/cookie-...
Deleting Cookies: expressjs.com/en/api.html#res....
Cross-Site Scripting (XSS): owasp.org/www-community/attac...
Cross-Site Request Forgery (CSRF): owasp.org/www-community/attac...
REST Security Cheat Sheet: cheatsheetseries.owasp.org/ch...
📚 Login References:
Bcrypt: www.npmjs.com/package/bcrypt
How to Safely Store a Password: codahale.com/how-to-safely-st...
MDN: HTTP Response Status Codes: developer.mozilla.org/en-US/d...
📚 More References:
Node.js Official site: nodejs.org
NPM Official site: www.npmjs.com/
Express JS Official site: expressjs.com/
MDN CORS: developer.mozilla.org/en-US/d...
NPM CORS: www.npmjs.com/package/cors
✅ Follow Me:
Twitter: / yesdavidgray
LinkedIn: / davidagray
Blog: yesdavidgray.com
Reddit: / daveoneleven
Was this tutorial about async await CRUD operations with Mongoose for MongoDB in Node.js helpful? If so, please share. Let me know your thoughts in the comments.
#mongodb #mongoose #nodejs

Пікірлер: 76
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
In this final tutorial for the Node.js for Beginners series, we update the CRUD (create, read, update, and delete) operations in our REST API route controllers with async functions utilizing Mongoose as an interface to our MongoDB collections. You will find that Mongoose makes our async CRUD ops much easier than they previously were when we set them up with JSON files. If you are just getting started, I suggest going to the beginning of this Node.js for beginners playlist here: kzbin.info/aero/PL0Zuz27SZ-6PFkIxaJ6Xx_X46avTM1aYw
@tigerseely3761
@tigerseely3761 2 жыл бұрын
Thank you, sir! Not only did I learn mongodb-related skills, but also a lot of best practices. LOVE the lessons!
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Happy to help, Tiger!
@stacybean1
@stacybean1 Жыл бұрын
Extremely useful course! Thank you Dave.
@benlee3905
@benlee3905 2 жыл бұрын
I love your teaching style, and the depth and detail you go into to explain the concepts and logic of your lessons, so props for you on that. On the subject of this series, if you ever do a multi-tenancy tutorial using node and mongoose, I would love to watch that. Thanks!
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Thank you for the kind words, Ben! 🙏💯
@deathdefier45
@deathdefier45 2 жыл бұрын
Thank you so much for making these wonderful comprehensive tutorials for free, I owe you for life.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
You're welcome, Ananya 🙏🙏
@youssefkarfouh3084
@youssefkarfouh3084 9 ай бұрын
thank you so muchhhhhhhhhh Dave . Simple and easy to follow
@tanbirhasanmohan6850
@tanbirhasanmohan6850 Жыл бұрын
Excellent explanation, Dave. I really enjoyed it, and it cleared up my confusion about JWT.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Glad it helped!
@umer5098
@umer5098 8 ай бұрын
Thankyou. It was very well explained.
@alienx2367
@alienx2367 2 жыл бұрын
Sometimes KZbin recommendation are priceless just like your channel 🙏
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Glad to hear it! 💯🚀
@adiemar3974
@adiemar3974 2 жыл бұрын
i'd love to learn more from you sir. it's been a great course. i hope youll make more videos like this.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Thank you, Adie! I will continue to make content like this 💯
@morchellemusic2829
@morchellemusic2829 Жыл бұрын
Hey Dave, great content, cheers from Barcelona
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Thank you! And hello 👋 to Barcelona!
@zackOverflow
@zackOverflow 2 жыл бұрын
This is Awesome, Thanks a lot.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
You're welcome! 💯
@mariusguissou4282
@mariusguissou4282 Жыл бұрын
👍👍👍👍👍👍❤ verry good playlist.
@aliimranadil2
@aliimranadil2 2 жыл бұрын
Love it sir ❤️
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Thank you! 💯
@mqashoo77
@mqashoo77 Күн бұрын
Thank You
@sonamohialdin3376
@sonamohialdin3376 2 жыл бұрын
So good tutorial thank you
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Glad it was helpful!
@sayidradhinpm8761
@sayidradhinpm8761 Жыл бұрын
Thanks a lot sir 🎉🎉
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Most welcome!
@flammablepez
@flammablepez Жыл бұрын
Awesome stuff per usual Dave, thanks a million. One question/request for you: When I created the userController I realized it would make sense for a user to be able to view/update/delete their own profile/password however I could not figure out how to implement it. I think it should be an OR statement when verifying the ROLES if the logged in person's id matches the profile they're trying to view/edit but thats as far as I've gotten. A follow up video thought or a code snippet suggestion/explanation would be most welcome if you have any time. Either way, thanks again for all you do!
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
You're welcome and thanks for the request!
@petstalkok
@petstalkok 2 жыл бұрын
Great tutorial! Dave, do you have any MERN stack tutorials or short courses with combination of React and NodeJS?
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
I currently have my React JS series and the Node JS series that this tutorial is a part of. If you search my channel for "full course" you will find both, too. I do plan to share some MERN projects, but you can take the projects from the React JS course and add Node/Express/MongoDB from the large REST API project in the Node JS course. Thanks for asking!
@charlieguillo7081
@charlieguillo7081 Жыл бұрын
Thank you so much for your tutorial Dave, it's really instructive! What about if we want to use another database, without the mongoose module ? With a database.js and dotenv file I mean Thanks
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
You can use other databases if you want. You have to apply whatever your chosen database requires.
@Pythonnaire
@Pythonnaire 2 жыл бұрын
Dave! you know one thing?...... I love you😍
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
As The Beatles sang.. "Love is all you need." 💯🙏
@Pythonnaire
@Pythonnaire 2 жыл бұрын
@@DaveGrayTeachesCode 😍
@kgetgamingentertainmenttec8243
@kgetgamingentertainmenttec8243 6 ай бұрын
Hi dave amazing tutorial i had run into a slight problem i am getting the req.cookies undefined in my refresh controller even tho it says one cookie after i login on thunder client i have removed secure:true i just cant figure out what the issue is any tips would be helpful thank you
@VIIITTTTTAAA
@VIIITTTTTAAA Ай бұрын
Спасибо Дейв, твои видео помогают мне развиваться и становиться лучше. Очень хорошая подача материала, доступно и интересно. Thanks Dave, your videos help me to develop and become better. Very good presentation of the material, accessible and interesting.
@shineLouisShine
@shineLouisShine Жыл бұрын
8 months later - it is still a great lesson, Although... A) Why chaining "req?.body?.id" (with two '?') in the first 'if' at 'updateEmployee", But using only a single '?' at "req.body?.firstname" (/lastname) in the second 'if'..? (instead of - not at all, or also two as before..) --- at 20:00 ---- B) Why using a 'try-catch' block when assigning 'result' with the created employee at the 'createNewEmployee' (const result = await Employee.create({...})), But not using a 'try-catch' block when assigning 'result' with the updated employee at 'updateEmployee', Or even including both of the update 'if' statements where you reassign employee.firstname and employee.lastname - Inside a 'try-catch' block, as you did when you created an employee. --- at 13:05 and 20:35 --- (* personally, as a person with ADHD and some OCD (just enough, for me, to be aware) - Such inconsistencies are putting me out of focus and are at least question-able.. Either if those are the conventions, best practices, or just a freestyle individual approach of yours -I'd be happy to hear what were your considerations by doing so..) C) I've seen so many teachers releasing themselves from the duty to type ';' at the end of every line of code. Yet you "insist" to keep doing so. How come..? D) You keep teaching shortcuts during your lessons, which are useful and great, Yet, I saw you cut-and-paste lines of code from outside a statement - into it - While it was located one line of code above it, And by simply standing on the line you'd like to maneuver and press alt+Up/Down-arrow - You'll get the same effect. All of those questions are coming from the desire to be a better programmer And are part of my efforts to leave behind as fewest holes of missing information as possible. I hope you can realize that, and not feel threatened or anxious by these. With all of that being said, You are a truly great teacher, sir. Throughout, professional, detailed, and methodical; And I really do appreciate the time and efforts that you put into running this channel. Sincerely
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Thank you for the kind words. Lots of questions about little things and as you mention... you might struggle with OCD or similar... and I can relate. That reminder at the end of my videos is as much for me as for everyone else.. keep choosing progress over perfection. So my answer to all is experiment with the code and choose the way you prefer to write it. I cannot let myself obsess over small syntax changes and I recommend the same to you so you keep enjoying what you do and continue to make progress. Again, I can completely relate to asking these questions.
@shineLouisShine
@shineLouisShine Жыл бұрын
​@@DaveGrayTeachesCode Oh, "keep choosing progress over perfection" isn't the full sentence... The full sentence begins with: "Remember..", and I do tend to forget this principle. Thank you for putting the spotlight on it again. I should really adopt it as a daily mantra... (...not only in programming).
@ruelporter1023
@ruelporter1023 2 жыл бұрын
I would like to know how to make a comment and rating system like the one amazon used for the products on its cite. I am wondering if you could add it as one of your projects?
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Thanks for the request! That's a good project idea💡
@kressplay
@kressplay 8 ай бұрын
great video i am sure i followed every step but i cannot perform any CRUD operation in the employees route
@eveypea
@eveypea 4 ай бұрын
I believe that Dave had populated the employees collection but did not film it
@nguyenanh-vt4jv
@nguyenanh-vt4jv 4 ай бұрын
mongodb or postgres, what should i choose dave
@DaveGrayTeachesCode
@DaveGrayTeachesCode 4 ай бұрын
Both are good choices. Do you know one already? Go with what you are most familiar with. If you are learning, it is good to know both.
@houseofcoding101
@houseofcoding101 Ай бұрын
Hey, Sir I hope you are good. I have one question. If user login he/she gets a access as well as refreshtoken and the same user login in another device/browser and then when the user first logged in that refreshtoken has invalidated as on login handler we generate the new tokens and save it in db. How can we overcome this problem. Sir please answer it. Thank you
@zomalee4512
@zomalee4512 2 жыл бұрын
Do you have a tutorial on async wrapper?
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Great question and request! I do not specifically although creating a useFetch or useAxios hook in React is kind of what that is. I could make one for Vanilla JS in the future. Here is an article describing one: dev.to/dewaldels/javascript-async-await-wrapper-22ao All of that said, you are asking in the comments of a Node tutorial and Node is already async so your usage may vary.
@yuanzeng5467
@yuanzeng5467 Жыл бұрын
Can someone point out which episode to watch to setup the .evn variables? Thank you!
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
I can't remember exactly, but I think it is around Chapter 10 or 11 when the auth discussion starts. View individual chapters here: kzbin.info/aero/PL0Zuz27SZ-6PFkIxaJ6Xx_X46avTM1aYw
@yuanzeng5467
@yuanzeng5467 Жыл бұрын
@@DaveGrayTeachesCode Thank you Dave! Your videos have been really helpful to my project! You are the best!
@ap7086
@ap7086 Жыл бұрын
Hi dave in your backend app, I can update created employess and delete them even after i logout using logout url endpoint. I did it using postman. But the confusing part is the refresh token saved in the database at login also gets deleted from database once i send the logout url but the issue is we still can update and delete employees even after logout Note that only if i try to manually log out using logout endpoint it happens within the 30s time frame i have given to the acess token but once the 30s time frame is over its works fine like we cant update or delete employees without logging back in. Is this the behavior of the app or a bug of mine or maybe yours. Most probably mine. Please can you reply fast
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Sorry the reply was not fast, but yes, I do not have that issue. You can compare your code to the source code linked for the lesson in the description.
@ap7086
@ap7086 Жыл бұрын
@@DaveGrayTeachesCode no i mean your app also have that issue acctually i found out thats not a issue. Because you said that the only thing we can do about logout in our backend is to clear the cookie and the refresh token and not the access token , so the acess token is handled at the fronted right? So i think that why without a frontend app clearing the access token i still can do crud operations at routes under verfiyJwt until the 60s of time i gave to my acess token expires right?
@mattdon6705
@mattdon6705 2 жыл бұрын
Mr Dave Gray sir, please I really need your assistance [God I hope he sees this], concerning a piece of code that I've been trying to fix for a very long time now. And I feel you are one of the people who can help me out with this frustrating bug. Okay, so it's basically a simple code I wrote in HTML, CSS and JS that involves two pages. [By default, the second page overlaps the first, but you can simply set the z-index of the first page to be higher so it sits on top of the second, the function will still work.] NOW THE PROBLEM: I designed the code such that: when I click on the body (or document) of the second page, the first page moves to the left (-100vw) and then sits on the second page (0vw, z-index:1) when I click on the body (or document) of the first page, the second page moves to the right (100vw) and then sits on the first page (0vw, z-index:1) (I used keyframes in CSS). When you view the effect in your browser you'll notice that at some point while animating from one page to the other, there will be a "jumpy" effect. At a point, the animation flows smoothly, then, at another point, it gives this "jumpy" effect (and that's really annoying) I WOULD SERIOUSLY LOVE TO HEAR YOUR RESPONSE, after which I'll immediately send you the code files. Oh, and you have my permission to feature the coding process on your KZbin channel. That way I'll be able to view it and make corrections. OR You can simply send me back the applied corrections via email: skyroxen@gmail.com [FEEL FREE TO CHOOSE EITHER OPTION] ---------------------------------------------------------------------------------------------I'm Matthew Don from Nigeria.
@Yoyo-sy5kl
@Yoyo-sy5kl 2 ай бұрын
Hi, I'm following the tutorial closely however I keep receiving a 403 Forbidden error whenever dealing with the employees collection. I am able to communicate with the db and receive data about users as well as the auth token. However, posting, getting or putting functionality appears to be broken. I'm wondering if there are any permissions that prevent this process from occuring, but that doesn't make sense since users collection is fully modifyiable.
@Yoyo-sy5kl
@Yoyo-sy5kl 2 ай бұрын
I figured it out. First, the database needs to have data inside of it. Second, extend the access token limit to 30s. Third create an admin, as a typical user doesn't have access. Test the user vs the admin, the user should receive an unauthorized error when posting, if they don't this is probably because the code expired or hasn't activated, I find that if you do this too fast it doesn't work. Then the admin should work. You can create a user with pre-specified role, the default role is a user, to create a user with admin or editor access you can only do this inside MongoDB compass. I think this is to prevent a foreign actor from assigning higher privileges' to the DB.
@murkyrainbow2747
@murkyrainbow2747 2 жыл бұрын
I am a beginner. Very good! after 204 status not emit message?
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
You can view the source code I provide with the resources link in the description. Compare my source code to yours to find the differences.
@redan684
@redan684 Жыл бұрын
Hi, based on some research 204 status will not emit a message. To see the message you need to make the status 200 ( I think)
@flames9350
@flames9350 Ай бұрын
25:22 did you just already put this data on the employee...? Because i don't remember you even showed in in the previous tutorial and this made me really confused
@shineLouisShine
@shineLouisShine Жыл бұрын
Thank you for the video. Maybe do you have an idea..(?) Right after "register" works just fine, 09:58 - auth doesn't. Instead, the server is disconnecting with a red letters notification (Status: ERROR) : "Connection was forcibly closed by a peer." And the terminal : " D:\Programming\Node-js\mongo_async_crud-main ode_modules\jsonwebtoken\sign.js:107 return failure(new Error('secretOrPrivateKey must have a value')); ^ Error: secretOrPrivateKey must have a value at Object.module.exports [as sign] (D:\Programming\Node-js\starterrs\mongo_async_crud-main ode_modules\jsonwebtoken\sign.js:107:20) at handleLogin (D:\Programming\Node-js\starterrs\mongo_async_crud-main\controllers\authController.js:26:34) [nodemon] app crashed - waiting for file changes before starting... " I couldn't find a solution for already hours now..
@shineLouisShine
@shineLouisShine Жыл бұрын
It seems like second parameter of - "const refreshToken = jwt.sign( { "username": foundUser.username }, process.env.REFRESH_TOKEN_SECRET, { expiresIn: '1d' } " - Is undefined. Why..?
@shineLouisShine
@shineLouisShine Жыл бұрын
I don't know why, but after lots and lots of experiments, It appears that the solution was to change the second parameter to a String. Means, from : const refreshToken = jwt.sign( { "username": foundUser.username }, process.env.REFRESH_TOKEN_SECRET, { expiresIn: '1d' } ); - To : `process.env.SECRET_TOKEN_KEY` , or - 'process.env.SECRET_TOKEN_KEY' , or - "process.env.SECRET_TOKEN_KEY" And that is the only way it works, or else it is undefined and occurs an error. But how is it in your code that it works properly?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
This solution is not correct. Did you create your own .env file? If you did, does your .env file contain a definition for SECRET_TOKEN_KEY ? If it does, did you require the dotenv npm package at the top of your server.js file? I show how to do all of these things in the video including how to use the node crypto module to create your SECRET_TOKEN_KEY value.
@shineLouisShine
@shineLouisShine Жыл бұрын
@@DaveGrayTeachesCode It's not significant but I accidentally changed the name of the key variable (after finding a solution to a post about the same error), but what I meant is that any String will work. `process.env.REFRESH_TOKEN_SECRET` , as well as putting it inside: ' ' or " ". - Sure, I've created an .env file and keys as you taught, and sure - require dotenv does included, as you taught. Actually, everything worked well on previous lessons. In this lesson, even after using your entire complete github code and add a .env file as you taught - this error still occurs while trying to execute a POST call with "auth" by claiming that the SECRET_TOKEN_KEY is undefined. Any idea why..?
@user-om5fu1vy1w
@user-om5fu1vy1w 2 жыл бұрын
I don't know why but when the became not sending cookies in my project Even when I clone your latest project mongodb_async it also don't send or get cookies even when removed secure : true option when I try refresh api I got 401 but there are no any console errors Please guide me if there any solution
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
I suggest going back through this video to see if you missed possibly missed a step. It all works as discussed in the tutorial 👍
@user-om5fu1vy1w
@user-om5fu1vy1w 2 жыл бұрын
@@DaveGrayTeachesCode any ways thanks you this series help me alot
@FelipeOliveira34910
@FelipeOliveira34910 2 жыл бұрын
see if you are trying a GET request instead of POST.
@xen0n20p7
@xen0n20p7 3 ай бұрын
Why am I getting 401 uauthorized error on post route even when I am using my admin user 😢
@Abe-Oluwatomisin
@Abe-Oluwatomisin 11 ай бұрын
Sorry the three videos has covered everything on mongo?
@Pareshbpatel
@Pareshbpatel 9 ай бұрын
{2023-10-11}
Intro to MongoDB and Mongoose | Node.js Tutorials for Beginners
17:06
Javascript Promises vs Async Await EXPLAINED (in 5 minutes)
5:50
Roberts Dev Talk
Рет қаралды 557 М.
Can You Draw A PERFECTLY Dotted Line?
00:55
Stokes Twins
Рет қаралды 100 МЛН
1❤️
00:17
Nonomen ノノメン
Рет қаралды 13 МЛН
ROCK PAPER SCISSOR! (55 MLN SUBS!) feat @PANDAGIRLOFFICIAL #shorts
00:31
Survival skills: A great idea with duct tape #survival #lifehacks #camping
00:27
I Stopped Using Express.js: Because Bun and Hono 🔥
10:23
Sam Meech-Ward
Рет қаралды 106 М.
JWT Authentication | Node JS and Express tutorials for Beginners
1:00:03
Build A Restful Api With Node.js Express & MongoDB | Rest Api Tutorial
53:55
How to Make 2500 HTTP Requests in 2 Seconds with Async & Await
4:27
John Watson Rooney
Рет қаралды 106 М.
tRPC, gRPC, GraphQL or REST: when to use what?
10:46
Software Developer Diaries
Рет қаралды 72 М.
CRUD API Tutorial - Node, Express, MongoDB
1:33:14
freeCodeCamp.org
Рет қаралды 184 М.
Swift API Calls for Beginners (Networking) - Async Await & JSON
25:35
Can You Draw A PERFECTLY Dotted Line?
00:55
Stokes Twins
Рет қаралды 100 МЛН