SignUp/Login Application With NodeJs, Express, and MongoDB (Part 1)

Serap Baysal
Geek Culture
Published in
7 min readMar 25, 2021

--

In this article, I will write about how to creating a SignUp Project with NodeJs and MongoDB. Let’s start.

I will use Visual Studio Code as compiler. In this project we need a package.json file. For this, in terminal, we’ll write

npm init

command. After that command, to fill our package.json, it want some informations. I leave it like that and just push Enter. I just need to change in package.json file, “main”: “index.js” file to “server.js”.

Than with npm install Express dotenv command will build Express and dotenv modules. So this commands create node_modules and package-lock.json files.

After that, I write npm install -D nodemon and install nodemon.

Our modules, seen in package.json file’s “dependencies” part. I need to do some changes in this file. In file’s “scripts” part, I’ll change ”test” to “start” and write :”node server”. So , our server start when I write npm start. Like that I write “dev”: “nodemon server”.

In main folder, I’ll create server.js file. This file will be our backend part’s main file. Than I’ll require Express and dotenv. After that, I will create Config folder and in this folder config.env. Inside config.env, just write PORT=5000, because this port our server’s running port.

So we can go server.js file. I’ll require env variables with dotenv.config({path:‘./config/config.env’}).

I create variable named app and use Express method, than with another variale named PORT write server’s running port.

After that, in app.listen() I’ll give PORT information and write in console.log `Server running on ${PORT}`. It take Port information dynamicly.

Our server.js file is look like that:

server.js

Than i’ll write npm run dev and server is running.

Now, we need to Postman. In Postman I’ll create a request and write server’s running address. In this tutorial I’ll use http://localhost/5000.

I’ll go to server.js file and use get method in Express. With app variable I’ll write

app.get(‘/’, (req, res) => {

res.status(200).json({success: true, msg: “Show all users”});

});

. I’ll run server with npm run dev and go to Postman.

Postman

That means, our code is success. Like that, we’ll write another methods too. All methods looks like:

server.js

Methods with /:id are working like http://localhost:5000/1 , others like http://localhost:5000 .

To this stage I run every method in server.js but it’s not true. So I create controllers folder, in this user.js file and move all methods with some changes. user.js file looks like:

routers/user.js

For update our project, we have to move codes in routes/user.js to controllers/user.js file and doing some changes in first file. You can run everything in server.js but if your project more than complex this project you have to do this changes.

controllers/user.js file looks like that:

controllers/user.js

So, what we will doing with routes/users.js file? First of all, we delete methods in this file. We require controllers/users.js file, with that first users.js file have this methods.

const {

getUser,

getUsers,

createUser,

updateUser,

deleteUser

} = require (‘../controllers/users’)

routes/users.js file looks like:

routes/users.js

Now, we go back to server.js file for our sending request’s seem in console. For this, we create a folder called middlewares and inside that a file called logger.js. This file have this code:

Const logger = (req, res, next) => {

Console.log(`${req.method} ${req.protocol}://${req.get(‘host’)}${req.priginalUrl}`)

next();

}

req.methods is (get, put..), req.protocol is http, req.get(‘host’) is localhost and req.originalUrl is / part. In server.js file, we write app.use(logger) and use this middleware. If you go back to Postman

, send a request and you can see method and url in terminal.

So we have to connect database. In this tutorial, we will use MongoDB. For that, we will create an account in MongoDB and generate a database, install MongoDB Compass, copy connection string. Connection string is look like:

mongodb+srv://<username>:<password>@cluster0.fxdx.mongodb.net/test

We change <username>, <password> and test parts. Test will be our database’s name, so you can give it a name as you want.

After this settings, we can connect to database.

npm install mongoose command will install entire package. We will create config folder and inside it, db.js file. We will go to the config.env file and create MONGO_URI variable, copy connection string. db.js file looks like:

config/config.env

After this file, we will go to server.js because we need to require db.js file.

const connectDB = require(‘./config/db’)

connectDB() will connect to database. In terminal, you can see MongoDB connected.

So, we can generate our model. We will create a folder named models and inside it User.js file. You can change as you want. I create like that:

models/User.js

Now, we have to create user. For this method we will do some changes in Postman. Firstly, we will go to Headers part, inside Presets click to JSON Content Type. We will click to Body part’s raw option. So we can request data to database. Before this, MongoDB Compass look like that:

We’ll go to controllers/user.js, change createUser function with this:

exports.createUser = async (req, res, next) => {

const user = await User.create(req.body)

res.status(201).json({

success: true,

data: user

})

}

We will go to Postman and Post a user.

We done createUser but I want to encypt the password. For this, npm install bcryptjs will install bcryptjs package and require this. Then we’ll write following code under our model.

UserSchema.pre(‘save’, async function(next) {

if(!this.isModified(‘password’)) {

next();

}

const salt = await bcrypt.genSalt(10);

this.password = await bcrypt.hash(this.password, salt);

)};

So, let’s see how can get all records in database.

exports.getUsers = async (req, res, next) => {

try{

const users = await User.find();

res.status(200).json({success: true, data: users })

}catch(err){

res.status(400).json({success: false})

}

}

getUser function:

exports.getUser = async (req, res, next) => {

try {

const user = await User.findById(req.params.id);

res.status(200).json({success: true, data: user})

} catch (err) {

res.status(400).json({success: false});

}

}

Difference between getUser and getUsers functions, is find() and findById() methods.

For update a user, we coding like that:

exports.updateUser = async (req, res, next) => {

const user = await User.findByIdAndUpdate(req.params.id, req.body, {

new: true,

runValidators: true

})

if(!user) {

return res.status(400).json({success: false})

}

res.status(200).json({success: true, data: user})

}

And deleteUser function:

exports.deleteUser = async (req, res, next) => {

try {

const user = await User.findByIdAndDelete(req.params.id)

if(!user) {

return res.status(400).json({ success: false });

}

res.status(200).json({ success: true, data: {} })

} catch (err) {

res.status(400).json({ success: false });

}

}

So, let’s see how can we do verification. Firstly we will create routes folder and inside that an auth.js file. Like this, controller/auth.js file will creating and we’ll go to this file.

We’ll require User model inside file, like that:

const User = require (‘../models/User’)

Then,

exports.register = async (req, res, next) => {

const { firstName, lastName, email, password } = req.body;

// Create User

const user = await User.create({

firstName,

lastName,

email,

password

})

res.status(200).json({success: true, token, id})

}

We’ll save that and go to routes/auth.js file and write:

const express = require(‘express’)

const { register, login } = require(‘../controllers/auth’)

And we’ll go to server.js file, and use in there.

const auth = require(‘./routes/auth’);

app.use(‘/’, auth);

Now let’s go to Postman and Post http://localhost:5000/register request. Result is success:true, that means it works.

We will use jsonwebtoken for data connection.

npm install jsonwebtoken

will install package. In controller/auth.js file, under User require we’ll write

const jwt = require(‘jsonwebtoken’)

const getSignedJwtToken = id => {

return jwt.sign({id},process.env.JWT_SECRET, {

expiresIn: process.env.JWT_EXPIRE

})

}

Then we’ll go to config.env file, write JWT_SECRET = anything, JST_EXPIRE= 30d.

Again in controller/auth.js file,we’ll write

const token = getSignedJwtToken(user._id);

and

res.status(200).json({success: true, token })

After these, when we go to Postman and send request, we can see token. Copy that token and paste https://jwt.io site, you’ll see under Payload:Data part id. If you compare this with in database, you can see they are same.

Finally we will login.For compare passwords we’ll again use bcryptjs. We’ll go to User model, and add new method:

UserSchema.methods.matchPassword = async function (enteredPassword) {

return await bcrypt.compare(enteredPassword, this.password);

};

Then, we’ll go to controllers/auth.js and create login. Create a folder named utils and file named ErrorResponse.js and paste following code inside it.

class ErrorResponse extends Error {

constructor(message, statusCode) {

super(message);

this.statusCode = statusCode;

Error.captureStackTrace(this, this.constructor);

}

}

module.exports = ErrorResponse;

We’ll require this file into controllers/auth.js and return to login.

exports.login = async (req, res, next) => {

const { email, password } = req.body;

// Validate emil & password

if (!email || !password) {

return next(new ErrorResponse(‘Please provide an email and password’, 400));

}

// Check for user

const user = await User.findOne({ email }).select(‘+password’);

if (!user) {

return next(new ErrorResponse(‘Invalid credentials’, 401));

}

// Check if password matches

const isMatch = await user.matchPassword(password);

if (!isMatch) {

return next(new ErrorResponse(‘Invalid credentials’, 401));

}

const token = user.getSignedJwtToken();

const id = user.getId();

res.status(200).json({success: true, token, id})

}

When we go to Postman and post a login request we can see success:true, token and id.

So that’s the final thing in this tutorial. Thanks for reading!

--

--