02Geek HTML5 and JavaScript, TypeScript, React, Flash, ActionScript online School
Previous VideoNext Video

Setting Up Node.js, Express, and MongoDB for Your Server

Building a reliable backend server is crucial for handling data in modern web applications. This tutorial will guide you through setting up a Node.js server integrated with Express.js for routing and MongoJS for connecting to MongoDB. You’ll create a practical environment to fetch data dynamically, perfect for testing and real-world applications.


Why Node.js, Express, and MongoJS?

  • Node.js: A fast, scalable server-side runtime that uses JavaScript.
  • Express.js: A lightweight library simplifying server management and routing.
  • MongoJS: A user-friendly, unofficial MongoDB driver for interacting with databases.

This combination ensures an efficient development process and provides flexibility for future enhancements.


Step 1: Setting Up Your Environment

  1. Install Dependencies:
    Run npm install in your project directory to install express and mongojs.

    npm install express mongojs
    
  2. Create Your Server File:

    • Name the file server.js.
    • Import the required modules:
      const express = require('express');
      const mongojs = require('mongojs');
      
  3. Start the Server:
    Use Express to create and listen on port 3001:

    const app = express();
    app.listen(3001, () => console.log('Server running on port 3001'));
    

Step 2: Connecting to MongoDB

  1. Specify your database and collection:

    const db = mongojs('ChartsDB', ['charts']);
    
  2. Create a route to fetch data:

    app.get('/chartjson', (req, res) => {
        db.charts.find((err, docs) => {
            if (err) {
                res.status(404).send('Data not found');
            } else {
                res.json(docs);
            }
        });
    });
    
  3. Test the route in your browser or API client by navigating to http://localhost:3001/chartjson.


Step 3: Handling CORS and Testing

To enable cross-origin requests for testing, include:

app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    next();
});

Run your server using:

node server.js

Check your console to confirm the server is running and test the API route to ensure data is being fetched from MongoDB.


Conclusion

In this tutorial, you created a Node.js server with Express.js and connected it to MongoDB using MongoJS. This setup lays the groundwork for dynamic data handling in modern web applications. In the next tutorial, we’ll integrate this server with a radar chart to visualize data from MongoDB!

Video Transcript

00:00In this lecture we're gonna go ahead and create
00:03and set up no JS with express JS
00:05and MongoDB to create a server.
00:08Basically no JS is to the server.
00:11Technology express JS is a library
00:13that helps facilitate easy interactions
00:16with no JS as a server.
00:18And last but not least, Mongo JS will enable us
00:21to communicate with our MongoDB that is running
00:24to fetch the information that we need.
00:27By the end of this lecture, you're gonna know the basics of
00:29how to set up no JS express JS at mongo js to work together.
00:36Okay, before we continue as a promised, let's talk about it.
00:40There are two folders for this section.
00:42There's the Mongo, the 0 0 5 Mongo,
00:45which is the continuation file from the last ending point in
00:490 0 4.
00:50And we have our server, which deliberately,
00:53I separated them mainly for one purpose.
00:57And that is to try to make our code a little bit more simple
01:01and not involve too much backend code.
01:03So with that said, let's take a look at
01:05what's inside of our server.
01:06And by the way, just make sure that you, uh,
01:08type in NPM install
01:10to install all the packages that are needed.
01:12And literally when you look into your,
01:14into the dependencies,
01:15you'll see all there is is express j express js it's called,
01:19and Mongo js, although it's called Express within NPM
01:23Express, enables us to basically more simply create servers
01:27or interfaces for our server while Mongo JS enables us,
01:32it's not the official driver of MongoDB,
01:35but it's the easiest driver and the most fun one.
01:38It's very similar. It's just a really good driver that I,
01:42I I use and I encourage you to as well.
01:45Now notice oto that inside of our main script this time
01:48around, there is a, in pur there is a point
01:50or purpose to the fact that our main is called server js.
01:54'cause that is our main file that we'll be working with,
01:57contrary to before where Webpac was really in charge.
02:00So it didn't really matter what we've put there.
02:02Okay, so let's go ahead and the first step, go inside
02:05of your server js and add the express file.
02:10Now it's going to, we're gonna require it
02:14and I'm gonna use because we're not using um, Webpac and
02:19because we're not using Babel,
02:20we're not gonna use any ES six here.
02:22We're gonna use standard JavaScript
02:24because that is what is currently supported in the point in
02:27time when I'm working in js.
02:30'cause right now we're creating a no JS application.
02:33The next thing that we wanna load is the Mongo js.
02:35And again, we're gonna have a require
02:37and we're gonna ask for Mongo js.
02:39So those are the two packages
02:40that we are basically going to be using.
02:43Now, express itself, we need a start up.
02:46And to do that, I'm gonna call the con,
02:48create a new constant
02:49by literally just calling express opening
02:52and closing a bracket, starting up our express application.
02:56The next thing that I'm gonna do is I'm gonna go
02:58Ahead and I'm gonna set up our database
03:01or make a call to our database.
03:04So for our Mongo js, what I want
03:06to do is I'm gonna set here the name of the database.
03:09Now the name of our database was Chart j chart
03:15DB I believe.
03:16But if we don't remember,
03:17we could go right back into our terminal and just go ahead
03:21and type DB to get the name of our db.
03:25So you see we have your uppercase charts, not chart
03:28and lemme go ahead and put that in there.
03:30And the next property is gonna be an array with a list
03:33of the different properties that we're expecting
03:35or the different, um,
03:37collections we expect to be working with.
03:40In this case, we're only expecting to work with charts.
03:42So I'm just gonna list that out
03:45and lemme just comment this out for a second.
03:47I wanna show you what every single, every single
03:51Express app needs to have to be able to start a server.
03:55All you really have to do is call the listen method
03:58into your app, which was created by Express and set an ip.
04:02So in this case, I'm gonna set the IP of 3001
04:07and I'm gonna go ahead and create here a function.
04:10And all this function is gonna do is just create a console
04:14console log.
04:16We are running on port
04:213001, okay?
04:22So we'll have a, a sub A message get coming back
04:25just whenever we start our server.
04:26So we'll know that we're actually listening to that server.
04:30Okay? It's time for us to build out the logic
04:32that will actually render out our database item.
04:36Now, to do that again, I'm gonna go to my app
04:38and I'm gonna set the path where you'll be able
04:40to gain access to our chart.
04:42And I'm gonna set it at chart json
04:44because it really is A-J-S-O-N element.
04:47Now I'm gonna go ahead and I'm gonna use E ES six.
04:49And by the way, I'm only doing this
04:51because I'm running in the really late, really
04:56new modern version of node js.
04:59So if you're wor running on an older version, make sure
05:02to not use ES six.
05:03But if you're taking this course, then it is a good idea
05:05for you to download the latest version.
05:07And I'm gonna use your Arrow function
05:10because I am actually with the latest version and
05:13because I'm with the latest version, I'm completely fine
05:15'cause there is no transcribing being done
05:17on this JavaScript.
05:19So now that I have my, my, my callback added
05:23or my my Arrow function that has a request
05:25and a response, it's time to me to actually approach my db
05:31and I'm gonna go to my charts
05:33and I'm gonna find that item
05:35that we've just stored here under below.
05:38And now to get it, I'm gonna send a request for the ID
05:41and then just send in a Mongo js,
05:46excuse me, and send in that object id.
05:51That's all I had to do to request that specific item.
05:54And the next thing I'm gonna do once I
05:56Looked for a find is I want
05:58to send another error function here.
06:00And this time around it's gonna be,
06:01or an error or a response.
06:04And I'm gonna start putting the logic right inside of here
06:07of what happens whenever a response comes in.
06:10So if there is an error, I don't really want to do much,
06:13so I'm just gonna go ahead and I'm gonna send a status,
06:16basically saying 4 0 4, I can't find the page,
06:18but maybe you would want
06:19to create something a little bit more sophisticated.
06:22Okay, so the next thing, and I'm just gonna go ahead
06:24and paste it and I'm not gonna dive too deep into it,
06:28but basically what this does, it it allows us to control
06:31who gains access to our server and in what way now,
06:35because we're gonna have our server acting in a separate
06:37place than our client,
06:39our server is gonna be running in port 3001,
06:42but our client is gonna run in 3000.
06:44They're actually communicating
06:45between two different servers.
06:47So these two lines will basically tell our server,
06:51allow anyone to gain access to your server.
06:54Not exactly the smartest thing
06:55to do in a production environment,
06:57but good enough for our testing purposes.
07:01Next thing I'm gonna do is I'm gonna go
07:02and I'm gonna send, using the response,
07:05I'm gonna send back our object.
07:07And our object is gonna be that in an array.
07:09So I'm gonna take the first item there,
07:11but ota, I'm gonna call the builtin JavaScript, JSON
07:15and go ahead and string ffi
07:19our value string fee.
07:21No, not string fee. So let's try this again.
07:24String phi there, right? I go.
07:27So let's just walk through what we've just done.
07:29So basically we're listening to Port 3001.
07:33Whenever the user tries to get something from chart js,
07:37we're gonna go ahead and search for the specific item
07:40that we want, which is the chart that we actually want.
07:43If the response we came back was not an error,
07:46we'll then allow access to anyone.
07:49And not only will we allow access to anyone,
07:51we're gonna send out that information, making sure
07:53that whoever's gonna load this up will a, will be allowed
07:57to manipulate the data that they're fetching.
08:00So with that said, let's go ahead and save this
08:01and go back into our, um, terminal.
08:05And let me search for terminal for our server. Here we go.
08:08And this time around, instead
08:09of typing NPM start, we're not gonna do that.
08:12That's because NPM start doesn't have any meaning anymore.
08:15But instead of that, I'm gonna type your node space
08:18and the name of the file.
08:19In this case I'm gonna load up our server.
08:21So node space server.
08:24Now if everything runs appropriately, we should see
08:26that we're running on port 3001.
08:29And now if we go into our browser
08:31and try to go to port 3001
08:34and then try to get into our chart js.
08:38Was it charts? No, it wasn't. It was chart J js o.
08:42And we should voila, get our JSON data. So there we go.
08:46So we have our data object ready
08:48and prepared for us in the next lecture.
08:52We're gonna continue down this
08:53path. We're done with the server,
08:54But make sure that you keep your server running.
08:57Don't close it. Make sure that your no DB is still running.
09:01Um, your, this area here, the driver
09:05for no DB is not important anymore.
09:07You could close it, but you do not want to close the
09:11Mongo D server,
09:13nor do you wanna close your actual server, port 3001.
09:16And in the next lecture we're gonna move into the 0 0 5
09:19Mongo finally and start connecting the dots, fetching
09:23that data into our charting component
09:26that we've already created,
09:27and see what beautiful chart is created from it.
09:32In this lecture, we set up a server, a separate server
09:34that will mimic a real world environment of a server,
09:37making it even better for our testing purposes.
09:41In the next lecture, we move back into the client
09:43as we create a radar chart
09:45and connect it to our data from our Mongo database.

Ready to Level Up Your Skills?

Join thousands of learners on 02GEEK and start your journey to becoming a coding expert today!

Enroll Now for Free!