Build A Restful Api With Node.js Express & MongoDB | Rest Api Tutorial
ฝัง
- เผยแพร่เมื่อ 5 ก.พ. 2025
- Check out my courses and become more creative!
developedbyed....
❤Become a patreon for exclusive videos and more!
/ dev_ed
Microphones I Use
Audio-Technica AT2020 - geni.us/Re78 (Amazon)
Deity V-Mic D3 Pro - geni.us/y0HjQbz (Amazon)
BEHRINGER Audio Interface - geni.us/AcbCpd9 (Amazon)
Camera Gear
Fujifilm X-T3 - geni.us/7IM1 (Amazon)
Fujinon XF18-55mmF2.8-4 - geni.us/sztaN (Amazon)
PC Specs
Kingston SQ500S37/480G 480GB - geni.us/s7HWm (Amazon)
Gigabyte GeForce RTX 2070 - geni.us/uRw71gN (Amazon)
AMD Ryzen 7 2700X - geni.us/NaBSC (Amazon)
Corsair Vengeance LPX 16GB - geni.us/JDqK1KK (Amazon)
ASRock B450M PRO4 - geni.us/YAtI (Amazon)
DeepCool ATX Mid Tower - geni.us/U8xJY (Amazon)
Dell Ultrasharp U2718Q 27-Inch 4K - geni.us/kXHE (Amazon)
Dell Ultra Sharp LED-Lit Monitor 25 2k - geni.us/bilekX (Amazon)
Logitech G305 - geni.us/PIjyn (Amazon)
Logitech MX Keys Advanced - geni.us/YBsCVX0 (Amazon)
DISCLAIMERS:
I am a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for us to earn fees by linking to Amazon.com and affiliated sites.
Twitter: / deved94
Instagram: / developedbyed
Github: github.com/Dev...
We are going to cover how to create a restful api using node.js express and mongodb together with mongoose.
Rest apis help us decouple our backend code from our front end so we can use it across multiple application (mobile apps, web apps, etc).
We are going to learn how to build a simple blog post type api with all the useful methods(GET,POST,DELETE,PATCH).
We use Node.js as our backend language, express.js is going to help us create routes easier and middlewares and we use mongodb together with mongoose to create schemas and models that define how our data looks.
If you are a beginner with nodejs, express or mongodb I hope that this tutorial will give you a good idea of how these technologies work well together.
🎵 Music:
Outro:
LAKEY INSPIRED - Me 2 (Feat. Julian Avila)
Music By: / lakeyinspired
Intro:
Dj Quads
Track Name: "Every Morning"
Music By: Dj Quads @ / aka-dj-quads
Creative Commons - Attribution-ShareAlike 3.0 Unported- CC BY-SA 3.0
creativecommons....
#mongodb #nodejs #express.js
For people visiting this tutorial recently, some important things to note:
1. MLAB is not in function anymore you have to use mongodb atlas.
2. the cluster by default will not allow write access so you have to set it up in settings.
3. At 44:00, remove function is deprecated so you have to use deleteOne function
Can you tell where we have to change the access exactly?
thank you so much! I was like wtf is going on? ahahahaha thanks a lot
Also id recommend using express.json() as a middleware instead of using body parser, since its built in
I’m a student studying CS at Ball State University, IN. I am not someone who would comment on a video on youtube because she likes it. This is legit the first time ONLY to tell you that nobody explains it better. All your videos, be it explaining hooks in React, cool animations or CSS, or this tutorial - they are all explained so well! Thank you for your content.
Please don't stop with this tutorials!! Super awesome for beginners like me.
Good luck friend, although I do not think that this specific tutorial is for beginners because if you already know about these techs then you're not a beginner anymore :)
Finally found a developer with humor , nice tutorial man
Honestly, I spend 53 minutes and 54 seconds of my life learning something useful. Thank you, Ed. You will have a good love life.
😂 you nailed it
I am taking my first steps into junior development.
I was tasked by my mentor to create an API with only 1 Route.
He asked for just a 2 tier database architecture as 3 might have been difficult for me to comprehend.
After a few hours of searching the internet, I stumbled across this video among other older videos.
This was the only tutorial that fundamentally taught me everything i needed to know and more.
Thank you so much for your help!
I cannot wait see what else I can learn in programming :)
Spent all day looking for someone to teach it in an understandable way, this ended my search. Thank you!
best course to learn about node js for beginners . Don't search for any other course just continue his technique it's worth a time.
1 Year later still the best tutorial. Just started NodeJs and this covered mostly all the concepts i needed to build an API. Keep up the good work!!
5 years later, still the best tutorial :)
I put this on for 10 minutes of background noise while I made my morning coffee and ended up transfixed for the whole thing. Your style is incredibly engaging, I laughed out loud a bunch of times and I could listen to your accent all day. Thanks a lot!
I loved your teaching style 😍😍.. Keep it up.. It helps us a lot
@Nikolas Ryker i have another scammers thanks alot
I was doing an online course on node js and would always freak out when it comes to connecting with Mongo db. Literraly stopped continuing on that paid course to return to TH-cam and learn it so well from this video. No wonders, you are a great teacher and have bright future. My best wishes and blessings for a great love life as well. Keep up the great work with the same passion and you will see miracles happening in your life. Thanks again. God bless you.
You are a really good teacher. You don´t just code away but actually take your time to explain what´s happening with each line of code. It makes it so much easier to understand!
Subbed.
Whenever I want to learn something from youtube I search that Keyword and starts watching that videos, but if I don't understand that, I just search for your channel and find that topic, and that's it.
thank you for making these educational videos. ♥♥♥
Ive watched many Node, Express tutorials. This is, by far, the best one Ive seen. Thank you!
hi i hope u can help me
why middlewares not working ?
app.use not working for me
Just created my first API with this tutorial. And, most important, not just copied your code but understood every step. Lott'a loving from Argentina man.
I really love people that teach code with character, it's so much engaging than being stiff and plain, thank you! Also you can use Yarn instead of npm haha
After investing money on udemy courses and countless hours of navigating through complicated documentation and tutorials accross the web, I was finally able to build my first REST Api with the help of this video and not only did I built it, I also grasped the fundamental architecture of the implementation of REST in Node.js world. Thanks a lot for making my day.
Liked, shared and subscribed! 😊♥
Magic!
Hi Ed, what happened to your Github account? Thanks for the great content!
i finally knew your trick after slow it down on 0.25 speed :)
Your teaching style never gets me bored. If I can only Subscribe on your channel for a thousand times I'll do it. Keep it up and may you never runs out of energy doing this.
I was building an API, and this taught me everything! Keep making videos about APIs! Thanks!
I don't even know why I look somewhere else, every time I want to learn something I go around for like half an hour and always end up on you channel lol
Dude, you're saving my life. Explained that even I understood whole flow and what each line of code is doing. You definetely should compete for a Nobel Prize or something. Thanks mate!
just another comment saying how good of a teacher you are... making me laugh while im learning is going to keep my attention longer and you are a part comedian too. thanks so much for your service!
Maaaannn you are my Hero! I struggled so long with all this stuff and finally I really really get it. Thx a lot for your tutorial! It was amazing :D
Can't even explain how simple and intuitive this code flow and explanation is. Content like this >>>>>
First time viewer here. Love the energy, passion and light hearted humor. Keep up the good work! I believe I got here from Brad Traversy recommending your channel.
this one hour video summarize three lectures that are 2h long on my collage. Appriciate your work dude! Thank you
Great tutorial, I'd love to see the front-end as a part two of this tutorial. Keep up the great work!
SIR This has got to be the most clear, concise and well made programming tutorial that I have EVER seen. Please keep making videos in this format. I can't express in words how helpful this video is for me. THANK YOU
Finally 1080p jesus...
@Jack Rong Nop , I don't think we need that
Nice videos.
Kindly, do a video on MERN
When you init npm add flag -y for standart settings ( npm init -y )
awesome thanks you ed
Just a quick question can we read data from already existing collection in mongo without creating schema?
Thank you so much buddy, Only left to learn for me was backend and you made it so easy. Now i can move on to my journey on becoming a full stack developer on flutter lessgo .. Love you man.
This is awesome! well explained, easy to understand and great tempo!
The way you teach is clear and easy to understand for newbies. Best JS tutor on TH-cam !!!!!!!
Awesome tutorial here, been looking for this RESTAPI with async await, it just came at the right time. I would like to see you go in depth with user auth and bcrypt. You just saved a soul
hi why middlewares not working ?
app.use not working for me
This is straight gas. studying for an interview and this is a massif lifesaver
YOOOOO lol you made me laugh so hard when you were like "I don't know why you would have a price." The way you gave attention to that was just awesome. "let me get rid of that." OMG laughing so hard.
"Good job package.json, you're doing your job!"
I spat my coffee laughing LOL
man, I was searching CRUD and everyone making tons of file structure & MVC style, I knew Express has a patch method but no one really used that ...Thanks man
I think that it will be cool if U make tutorial for authorization (registration, login) app with some other features (for example,using React for front), and show how to integrate that with backend. Thank u for great explaining.
up for this or btw angularjs
guys can some one share working code please (github) devE's link for github in description doesent exist i am having issue writing data to database but i am not getting any errors couldn't figure out trying very hard
@@SivaNare did you find it? i post data from postman but it gives an empty error message while it's not responding the data back.
@@ege2026 i can help
for those who are getting error or say the /posts is not loading then just write
// Middlewares
app.use('/posts', (req, res, next) => {
console.log("hello this is a posts middleware");
next()
});
the next function removes the discontinuation to the get handlers which are below the app.use middleware
Hey Anshuman, thanks for that tip! have you completed many projects in node? Are you a 2021-passout and open to opportunities in web development currently?
For people having trouble around the 33:00 minute mark when trying to commit a post via Postman I suggest checking your name and password is correct on your mongoDB link.
Its totally correct but still not working
U are right man. It´s a big confusing, but I got it
Thanks.
@@kiranmahajan778 Have you solved ? Commit (save method) is not working and no error message is displayed!
here the solution: check if your ip changed, update your whitelist in the mlab, then it should work
@@robertoradu9965 okay i will try!
Before, I was a PHP Developer. I want to improve my skills in the Back-End area. After a long time of pondering, I want to move to NodeJS.
Thank you for making this great video. I can understand your explanation very easily.
Greetings from Indonesia~
This one is cool tutorial. To the point.
Btw, mlab has been acquired by Mongo atlas. So, everything has been changed
Not really, Mongo atlas is almost identical and it is very easy to go along with the tutorial
No beating around the bush. Straight to the point. Loved it!
I'm following along the tutorial but Postman is stuck at "Sending" @ 34:12
It prints console log message but nothing with mongoDB... I see nothing nothing updated in MongoDB atlas too.
Please reply as to what could the solution to the problem be?
Same
Check your DB connection string
same problem. I tried retrieving the connection string again, no luck. seems to be a problem with the promise, or postman not working with the db. my postman console log shows Error: socket hang up on the post requests im sending after they fail - looked online for context/resolution, not much help.. only thing i could find that might help is about making sure the proxy is configured correctly. thats outside my wheelhouse, i just made sure to turn off any proxy in postman via settings>proxy, still no luck.
Hi. I am facing the same issue. Do u guys able to find a solution?
I had the same issue. It took me hours to catch the issue.. I spelled mongoose with a capitial "M" as in const mongoose = require('Mongoose') thus all of my db operations timed out.
You are great. The way you are teaching is awesome. This is the first time I watched a whole tutorial video. Thank you for teaching all these in a simple way!
Hey I'm getting error on the time interval of 33:47 to 35:54
were there is new (first) data generate for the mongoose with post. For me its just going into the ".catch" instead of the ".then"
did you manage to find the solution to this? im having the same issue.. :(
@@kristboshnjaku135
try {
const savedPosted = await post.save();
res.json(savedPosted);
}catch(err) {
res.json({ message: err });
}
@@kristboshnjaku135 Try this out and also one more thing make sure you have your ip address connected to the altas mongo db because when you run on localhost it won't with just db user and password you will need to config the ip address.
@@kristboshnjaku135 These 2 thing resolved my issue.
@@jaydesai1430 hi Jay, sorry to say but this didn't help; still catching the error not the post itself in Postman.
Love your intro sir! I was actually really stressed out about the project my Lecturer gave me regarding these topics and i kinda fed up with it because ive been stuck since forever. Your intro cheered me up and help me see these stuffs in a better way! definitely gonna watch till the end
use mongodb atlas instead of mlab, cause is has been acquired, great tutorial
By MongoDB
Mlab is Now part of the MongoDB family... so atlas too :)
can anyone tell me how to do that??
@@sahelee1 did you know how to do that?
Couldn't wrap my head around even the basics of Express until I watched this. Excellent tutorial.
Don’t be emotional 😂 Thank you for this good tutorial!
ur a great teacher. ur energy too. usually i start getting sleepy at other tutorials but urs is great
Let me guess the one dislike on this video is a PHP developer.
😕 I don't think so.. I am PHP developer, but I have always wanted to start with something like this. This guy is a hero for me. I have immediately subscribed and liked this video. I wish he had zero dislikes.
Php devs don't love themselves
@@ajricherson1099 We don't love our selfs but we are selfless!
@@peefg no, probably thats Java guys
wow that's not sarcastic at all!!!!
What an awesome tutorial. I literally went from 0 to having a functional REST API with this and no other JS/NodeJS background.
If you cant connect to mongoDB with mongoose (like me!), make sure that your IP is whitelisted under the "Network Access" Tab
Thank you.. was also struggling the same
somehow this syntax at 29:13 worked for Ed but not for me...
router.post("/", (req, res) => {
console.log(req.body);
});
...when sending a POST request with Postman, I could not get any response
SOLUTION:
router.post("/", (req, res) => {
res.send(console.log(req.body));
});
INSTEAD OF
router.post("/", (req, res) => {
console.log(req.body);
});
I have no idea what I'm doing but this worked for me !
did you manage to find the solution to this? im having the same issue.. :(
facing same issue.. i am just getting:
{
"message": {}
}
@Krist Boshnjaku and @Ayesha Shabbir
Did you try
res.send(console.log(req.body));
INSTEAD OF
console.log(req.body); ?
That worked for me three months ago.
Yes I tried res.send at first but it didn't work ..so just for checking I changed it to console.log to see whats happening.
@@Scapben i'll check it again!!
I REALLY like that you don't fix typos in words or etc because really, who cares. We're here to learn how things work, not to perfect grammar!
Please make a full tutorial building a chat app with React and Firebase! :)
It would be really helpful!
You are literally my favorite teacher on TH-cam. You know how to dumb things down to let everyone understand it. Thank you Ed for making things simple!
Hi, I'm having problem with postman. Its returning me "could not get any response" when posting "my first post" but prior to that it is showing in the terminal. What could be wrong?
I'm having it too, did you solved it?
then kindly tell me the solution.
did you manage to find the solution to this? im having the same issue.. :(
i used to watch this video and yet couldnt understand(because i was really beginner at coding) and recently learnt how to build an api with GO, and its actually easy, and now i come back again watch this video, and finally understood what those code do, i mean thankyou for video, ts great. and for people who struggle with JS, Go is trully beginner friendly. thanks
Hey man, I need help. I am totally new to Express+Mongo, I have done exactly what you have showed. Its getting connected to database too. But when I am trying to post(save) data to database, its not showing any result( res.json(data) is not coming up in postman). What I think is happening is I have not mentioned the collection name. Do we need to specify the collection name too in Schema. if yes, could you please provide me with full details. Thanks in advance
Did you manage to fix this??
@@chanellesesh4977 yes. We need to pass the collection name as a parameter if the collection is already created in the database. In my case, I wanted to use one of the collection already provided in Mongo Db Atlas. So I just pass the name of the collection as a parameter in the Schema. That's it.
@ yeah sure
const GradesSchema = mongoose.Schema({
recrd : {
type : String
},
vesslterms : {
type : String
},
feature_type :{
type : String
},
chart :{
type : String
},
latdec :{
type : Number
},
londec :{
type : Number
},
gp_quality :{
type : String
},
depth :{
type : String
},
sounding_type :{
type : String
},
history :{
type : String
},
quasou : {
type : String
},
watlev: {
type : String
}
}, {collection : 'shipwrecks'});
The 'shipwrecks' being the collection name.
@ are you giving the right database name in the connection url? Change the 'test' part with your database name in the connection url
{ useNewUrlParser: true, useUnifiedTopology: true }, add this to your app.js file inside mongoose.connect
You are one of best teacher i had ever seen ... I myself also educator ..on serious note the way you explain is really simple connecting ...
Its easy to understand and covers every major concept...
Thanx sir for this contribution ...
Looking forward to get more and more knowledge from you sir . 🙏
10:40 "It says to connect use driver blah blah blah blah here" ... This is pretty much how I read documentation..
This is the most productive video I’ve seen in TH-cam in my entire life
When I post, the json file comes only with message={} , and it doesnt post anything to mongodb atlas. Help
did you manage to find the solution to this? im having the same issue.. :(
@@kristboshnjaku135 I manage to fix it:
const express = require('express');
const router = express.Router();
const Film = require('../models/Film');
router.get('/', (req, res) => {
console.log("We are on films GET");
res.send('We are on films GET');
});
router.post('/', (req,res) => {
console.log("We are on films POST");
console.log(req.body);
res.send('We are on films POST');
});
module.exports = router;
just edit films to whatever u want
@@santiagowhite5467 You managed to run the code and get the console.log work, but did you actually manage to insert your data to the db? that's the problem here...
@@kristboshnjaku135 I did, I suggest you watch a more recent video by Dev Ed in which he uses mongodb atlas, where he takes all steps necessary to ensure connectivity with db. The name of the video is “build a nodejs api authentication (...)”. He builds a rest api aswell.
@@santiagowhite5467 Ok, I'll give it a try... I'm still confused why it's just catching the error instead of the data first :p At least I can get it working..
Much appreciated bud!
Dev, u just made my undderstanding of rest API much easier, just 15 min into your vid and am loving your presentation. thank you sooooo much...
I'm following all the way up until 34:00(ish) for some reason when in postman I can't see the object created with the id, title, desc, etc"
You need to put const bodyParser = require('body-parser'); ABOVE const app = express(); and it should work - took me 2h to figure it out and it's not in the vid
@@mattbra1397 in postman use x-www-form-urlencoded mode dont use raw its work it to me
@@BodrumDrone thanks for the info - we got now two solutions to the issue :)
@@mattbra1397 i follow all information about solution.
i get postman to console the first post but when i try to get it in postman it gives me only the error part. i tried with x-www-form-urlencoded, same thing. looked online for other solutions, nothing worked
Sir you are a man with great skill and good humour
Hello Vivek, are you a 2021-passout and open to opportunities in web development currently? Have you completed any projects ?
Hey Ed, are you pretending to create a frontend tutorial to interact with this REST API ?
Apart from being a pretty interesting teacher, you just make me laugh. You have a great personality and vibe
Seriously, I love this channel. It's just refreshing to have interesting/funny full-stack instruction, for a change.
It's the first online course that got me excited about coding.
u
hk;
This tutorial is better than other plenty of hours of videos i've watched... Thanks for making this !!
The fact that I subscribed just after watching your intro ??
Bruhhhh... Love your energy
You're the best teacher for NodeJS REST API on TH-cam :D thanks a lot
Unbelievable ! A course 3 months in college is covered in 50 mins. You made my day bro !!
and after 7 months strugling i got the concepts of crud application guy u r awsome
Hey Abhishek, have you created any applications using node? Are you a fresher and open to job opportunities in web dev currently?
@@shivanigaddagimath2143 yes
@@Peaceinhills Hi Abhishek, if you are interested in knowing more about this opportunity, please get in touch with me using the info on my channel.
@@shivanigaddagimath2143 okay
entertaining, short, tips and tricks every thing in a single video, thanks devbyED.
Your love life is great cause you are giving alot of informations to people and they actually love you and your style. Keep it up man!
I love this guy & his content. He's good at explaining everything and he makes them look like a piece of cake when it's actually the opposite.
This is tutorial perfect, this is what I have been looking for for a long time. Thank you from VietNam !
I'm getting an error named post.save(..).then(..).catch() is not a function can you help me out with this plzzz
i`m beginer from Vietnam. And this video is very usefull to me . thank you and i hope your life now is great :))))
your tutorial is the best I've found, and I want to express my heartfelt thanks for your excellent teaching.
You literally make the best tutorials on TH-cam
I dont know how i thank you! you just teach me nodejs , express js, mongoDb. by the way i am an native android developer and flutter developer. from now I am a node js developer to.... thank you DEV
Great turotial! Btw, for whom watches the video today - remove() is deprecated. Insted use deleteOne() method.
You're so awesome! I never imagined that I can quickly understand the CRUD in RESTful API until I saw your video. Thank you so much!
You are the most fun youtube teacher I have ever seen
Now you're my favourite TH-camr 😍 a whole month of my life in less than and hour
I'm new to all of this. I have been taking courses on these very topics, Node.js, MongoDB, and API creation, and maintenance. I'm not done taking courses, but this has definitely helped me better understand how I can create my own website.
Great video. Thanks heaps. The entire video was both entertaining and instructional but, to me, the cherry on the cake was the little CORS bit. Many a time I had the feeling that dealing with CORS issues was an obscure arcane practice. Who’d have known the problem was so easy to solve? Thank you and regards from Brazil.
You just got yourself a new subscriber and a fan thanks for this, I've been struggling with this for months..
My first time commenting on a tutorial video coz this was the most entertaining and fun I've watched. Keep up the great tutorials! :D
Initializing project 0:00
Including express 2:35
Creating routes 3:45
Middleware 6:17
Connect to MongoDB database 8:24
Creating models and API calls 20:33
POST Requests 25:00
GET Requests 38:33
DELETE Requests 42:41
PATCH Requests 45:34
you look sooooooo happy, and it really makes student like me feel relaxed.
Damn. Just found this video (yet to watch) .. Just went from a class where I couldn't figure ANYTHING OUT... And you have a solid history on making me figuring things out!
sadly Can't make an account on mLab anymore.... so... it's gonna get hard to follow =\
love your tutorials! I wonder why I don't learn at all at my super expensive Bootcamp and always have new developers guilty feelings of "am i stupid!!?" but learning with your tutorials is fun, interesting, and easy! seriously thank you!! a lot AAAA LoOoT!
For anyone doing this now, when you can't just use mlab but have to use Atlas:
You need to click connect your cluster via application, copy and paste that string. In addition, you might have to create a DB for that cluster if you haven't already.
To do this click the collections button on the cluster and then hit add a database.
You are an absolute legend for this! Postman kept returning no data on the post request and I was about to give up
I like your teaching style. It's a very useful video for backend programmers. love from India.
Чувак (вижу что наш)... вот ты первый кто взял и весь путь показал в этой связке . love you ))