Section 31 – Lesson 398 – Complete 2020 Web Development Bootcamp

Lesson 398 – Level 1 – Register Users with Username and Password

The first step is to install mongoose in the project directory folder. You type the following code in the terminal –

npm i mongoose

Then you require mongoose in the app.js file using this code –

const mongoose = require("mongoose");

We then use mongoose to connect to our mongoDB database using this code –

mongoose.connect("mongodb://localhost:27017/userDB", {useNewUrlParser: true, useUnifiedTopology: true});

The next step is to set up the new userDB database. First we set up a new userSchema like this –

const userSchema = {
	email: String,
	password: String
};

Then we use the userSchema to set up a new user model –

const User = new mongoose.model("User", userSchema);

In order to catch info submitted by the user, you have to then create a new “/register” route –

app.post("/register", function(req, res) {

	const newUser = new User({
		email: req.body.username,
		password: req.body.password

	});

	newUser.save(function(err) {
		if (err) {
			console.log(err);
		} else {
			res.render("secrets");
		}
	});

});

The last step is to create a new “/login” route to allow previously registered users to login. This code does that –

app.post("/login", function(req, res) {
	const username = req.body.username;
	const password = req.body.password;

	User.findOne({email: username}, function(err, foundUser) {
		if (err) {
			console.log(err);
		} else {
			if (foundUser) {
				if (foundUser.password === password) {
					res.render("secrets");
				} 
			}
		}
	});
});