02Geek HTML5 and JavaScript, TypeScript, React, Flash, ActionScript online School
Previous Video
Chapter is concluded.Next is

Creating a full registration with MongoDB

Creating a Full Registration System with MongoDB

In this tutorial, we will build a full registration system by integrating MongoDB into our React-based application. We'll walk through connecting the necessary components, validating user input, and ensuring our database stores user information correctly. By the end of this tutorial, you'll have a fully functional registration system using MongoDB, React, and Node.js.

Note: This tutorial was initially created in 2016. Since then, newer versions of MongoDB, Node.js, and related packages have been released. For newer projects, you should use the latest versions and consult updated documentation.

Step 1: Connect to MongoDB

The first step in creating a registration system is to connect to your MongoDB database from your Node.js server. We use the mongojs library to do so. Here’s the basic setup:

const mongojs = require('mongojs');
const db = mongojs('mySite', ['users']);
  • mySite is the name of the database we’ll be working with.
  • users is the collection that will store our user data.

Step 2: Handle the Registration Request

We start by handling the HTTP POST request to register a user. This involves setting up an endpoint in our Node.js server that processes the user's email and password.

app.post('/register', (req, res) => {
  const email = req.body.email;
  const password = req.body.password1;
  const confirmPassword = req.body.password2;

  // Validate Passwords Match
  if (password !== confirmPassword) {
    return res.render('register', { error: 'Please match passwords' });
  }

  // Check if User Already Exists
  db.users.count({ email }, (err, count) => {
    if (count > 0) {
      return res.redirect('/login'); // User already exists, redirect to login
    }

    // Insert New User
    db.users.insert({ email, password }, (err) => {
      if (err) {
        return res.status(500).send('Database Error');
      }
      res.send('User has been added');
    });
  });
});

Key Points to Note:

  • Password Validation: We double-check that the password and confirmation password match before proceeding.
  • User Existence Check: Before adding the user, we verify if an account with the same email already exists.
  • Insert User: If the user doesn't exist, we insert the new record in the users collection.

Step 3: Running and Testing the Registration Flow

Once our registration endpoint is set up, we can test it. To test, start your server using the following command:

npm start

Navigate to your registration page, fill in the details, and click submit. The server will either ask you to match your passwords, redirect to login if the user already exists, or successfully register the user.

Handling Common Errors

  • MongoDB Connection Issues: Make sure MongoDB is running before starting your server.
  • Server Errors: If you see unexpected tokens or runtime errors, ensure all conditions are closed correctly, as these errors often result from unbalanced brackets.

Note: The password storage in this tutorial is simplified for the sake of learning. In a real-world scenario, use a library like bcrypt to hash passwords before saving them to the database for security purposes.

Homework: Expanding the Registration System

After completing the registration flow, here are some next steps to enhance your application:

  1. Create a Login Flow: Implement a login endpoint where users can log in using their credentials.
  2. Add Authentication: Learn about session management and implement session-based or token-based authentication.
  3. Idiomatic JavaScript: Convert the code you’ve written into more idiomatic JavaScript, making use of modern best practices.

These additional features will help you solidify your skills and make your registration system more robust and secure.

Conclusion

Congratulations on completing this tutorial! You now have a fully functional registration system integrated with MongoDB. Continue practicing and exploring new features to become more comfortable with full stack development. For more tutorials, visit: https://02geek.com/category/react/fullstack.

Happy coding!

Video Transcript

00:01So far we worked with Babel
00:02where only our React components use them.
00:05But in reality, you know now newer versions of JavaScript,
00:08why not integrate them everywhere inside of Node?
00:11Beyond that, we weren't really efficiently using Babel.
00:15So instead of that, I'm gonna show you the steps involved in
00:17a really clean setup of Babel
00:20and show you really the best way
00:21or a better way which you're gonna love.
00:24And this is really gonna be the way
00:25that you're probably going to use Babel,
00:27but you're gonna have a really good understanding
00:29of all the different ways
00:30that you could use Babel by the end of this lecture.
00:34To save us a bit of time, I pre-typed here
00:36and I'm gonna type on enter
00:37'cause it takes it a bit of a while.
00:39And what we're doing here is I'm installing into our dev
00:42environment, not our production environment with Save Dev
00:45Babel client Babel preset ES 2015
00:49and Babel preset React.
00:51Okay, now I, I'm gonna go ahead
00:53and I already Oto did another something
00:55to save us a little bit of time,
00:57which was in our React server directory.
01:00You'll find a Babel Source Source file, create that file.
01:04As things are installing, I wanna go ahead
01:06and show you, basically this is the configuration for Babel
01:10and what we're actually going to do is we want to tell Babel
01:12to basically wrap up
01:15and convert our code inside it
01:18before our application even starts,
01:20before Node even starts making it possible for us
01:23to use really cutting edge features into React even to Node,
01:27into React even if they don't support it.
01:30Now, if you know a lot of newer JavaScript
01:32or plan on learning it, make sure to check other presets.
01:35So these two presets that we're installing
01:37that we're in the process of installing right now, one
01:39of them will give us access to ES six in the world
01:42of ES five and another one will give us conversions
01:45from React itself.
01:46Like one of those conversions are the capability of instead
01:49of typing here class name to be able
01:51to just type class and it would still work.
01:55Another thing that I want to um, just fix here
01:57before we wrap things up, notice that we forgot to delete
02:00that React dom server part here.
02:02'cause we have exports, we don't wanna render anything
02:04that would break our application.
02:06So just go ahead and delete that from your auth file.
02:09Alright, so we have our Babel source.
02:11We set the presets in plural, not a singular, uh,
02:15to be ES 2015 and React.
02:17Let me go ahead and make sure that it's saved.
02:20Um, another thing that I'm, let's go ahead enter our server
02:22and start actually using our auth that we've created.
02:25And to do that I'm gonna go ahead and I am going to call it
02:30and actually add it into our library.
02:32So I'm gonna go ahead and require it
02:34and I'm just gonna give it a name, let's call it auth view,
02:37just to differentiate it from any real auth
02:39things that we might have.
02:41And I'm gonna just type here the folder that I'm in,
02:43which is gonna be, or the source or the build.
02:47And there I'm gonna go to my react
02:49folder 'cause that's where it is.
02:51And we're gonna go into our auth requesting that component,
02:54making sure we end everything with a comma
02:57in our register section.
02:58Let's go ahead and also create that variable
03:01and define that body.
03:02So I'm gonna go to my auth view register
03:05and I'm gonna just send some message from here.
03:07This is a message from the server.
03:11So if I'm just gonna make sure that I also pass it instead
03:14of typing hard coded values to the values that I'm sending
03:18to the EJS templating world.
03:21And if I save this, and just before we test this out,
03:23after we make sure that everything is running, uh, I want
03:26to walk you through the flow.
03:27So we're loading up the React JS class.
03:32We're then o to using it by calling the
03:36exported only function
03:37that exists in auth, which is this register.
03:39That one already on its own is wrapping around
03:41that DOM server and rendering everything out.
03:44By the way, if you were gonna create JavaScript
03:47that would work on the server
03:48and the client, well this, you would never put inside
03:51of your inside of this area
03:53because if you would, this is tying it to the server.
03:56But if we would put this inside of the server area
03:58and keep this clean, then we could use the same auth file
04:01for both the client and the server.
04:03But in this case, we're kind of tying it
04:04to the server itself by doing this.
04:06Okay, so that's really the process
04:09and all that's really left for us
04:10to do is to test things out.
04:11But let's check if and see if we're done
04:14with the installations.
04:15And I believe that we are.
04:17So now that we're done with the installations,
04:19let's go back into our editor and I'm gonna go
04:21and I'm gonna reload
04:22because now we're gonna Otto have here some, um,
04:25dependencies that were added in.
04:26And by the way, as I was playing around
04:28with things while you were away,
04:29I Otto added in here two things.
04:31And I want us to walk through them
04:32and understand what's inside here.
04:35One script I added, which is called Build.
04:37We'll basically call babble
04:39and ask it to take everything in the source directory
04:43and convert it into the build directory.
04:46And then I've created also the
04:47start, which we've met before.
04:49And the start, we'll actually do that process again
04:51by calling Build again, running the command NPM Run build
04:55and then run the actual server.
04:57Let's break it down and see the build process itself.
04:59So if I go into Terminal, now that everything is loaded
05:02and I write NPM Run, I could type in any name of any script.
05:06And this case, because I've created the start the build
05:09script, I could go ahead and just type here build
05:12and what will happen, it's gonna run the
05:13command within Build.
05:15Now the reason why I'm doing it this way,
05:16I'm not typing the command directly here
05:18and look how it transcribed
05:19and converted all the two JavaScript files
05:22that we had in those directories.
05:24The reason why I'm doing it this way is
05:25because when it's inside the script is inside
05:28of this folder, then has access
05:30to all the different folders, all the different bins inside
05:33of node modules, making it easier for me not to need
05:35to reference the different directories and sub directories.
05:38'cause I could just say babble
05:39and it will know what I mean,
05:40which it wouldn't if I would go into my root directory.
05:43Okay, so now that I built it, I want to just show you an,
05:46uh, I wanna also make sure that our, uh, uh,
05:49the build itself, I'm setting it also
05:51to the build server js.
05:52That's something I've changed in between as well.
05:54Um, what I wanna do now is I wanna show you what
05:56Would happen if we would run our server.
05:59So if I go ahead and I do, um, node
06:01and I run our source instead of running our deploy
06:04and I call our server,
06:06what will happen is basically it's gonna get an error.
06:08It's gonna tell us, well, I don't recognize this token that,
06:11that XML stuff.
06:12I don't really know what to do with that.
06:13I don't support that. Okay?
06:15But if I go ahead now
06:16and I, instead of running my source, I go to note
06:18and I ask it to run the build
06:20and go to the server there, then it's gonna know exactly
06:22what to do and our server will run.
06:25Now last but not least, lemme just stop this, clear it out.
06:28Be we could just call NPM start.
06:30And if we call NPM start, what's gonna actually happen?
06:33It's gonna go ahead and build us out using
06:35that NPM run build and then start up our server.
06:38So if we go ahead here and just type enter
06:40after we typed NPM start, it's gonna first convert our build
06:44and then run our application.
06:45Now one of the most powerful things about
06:47what we've just done right now is
06:48that all these dependencies
06:50of configuring Babel are happening outside
06:52of the actual live server, which basically means
06:55that we're gonna pre-compiled everything,
06:57reducing the strain inside of our application.
06:59We don't even need to mention babble inside
07:02of our server itself or anywhere in our application.
07:05And we could even serve up our, our React if we wanted to.
07:09We could serve it up as regular JavaScript without needing
07:11to do any conversions on the browser
07:13or on the server itself, which is the best way
07:17to work with Babel.
07:18With that said, let's take a peek at the server.
07:20And here we go. Our server should now be rendering our full
07:24registration, sending in our error
07:26message in this lecture.
07:29We really learned the best way to work with Babel six.
07:33And in the next lecture we're gonna continue on
07:35completing the creation of a full registration with the help
07:39of Mongo dp.

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!