SignUp Function with NodeJs and MongoDB(Final Version)

Serap Baysal
Geek Culture
Published in
3 min readJun 3, 2021

--

I wrote about this function and others, but while I writing the project wasn’t finished. So, I finish project and want to explain how to do it. Let’s start!

Firstly, we need to create a database in MongoDB. For this, we’ll use Schema. In this project, I have three databases. We’ll begin with User Schema.

To creating a schema, we’ll require mongoose. Then we’ll write this code line.

const UserSchema = new mongoose.Schema({})

In database, we have name, email, password, point, randomCode, login, forgotCode, id, imageUrl and refreshToken. Random code is for activating account, forgotCode is for reset password and refreshToken is for reach in other pages like account. Name, email and password is required and I use following regular expression for checking email format.

/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/

In schema’s end, we’ll export model with this:

module.exports = mongoose.model('User', UserSchema);

We’ll use ‘User’ in other pages. I’ll create a folder named controllers and in folder create a file named auth.js. In auth, we’ll require User Model and nodemailer. Nodemailer is for sending emails to addresses. We’ll create a variable named transporter for nodemailer. Then we’ll create an email address and use it for nodemailer.

var transporter = nodemailer.createTransport({service: 'hotmail',auth: {user: process.env.NODEMAILER_USER,  // in .env filepass: process.env.NODEMAILER_PASS // in .env file}});

Now we’ll create async register function. In this, we’ll let a token and equals at the random number with 6 digits.

let token = Math.floor(Math.random() * 999999);

Then let refreshToken and define const name, email and password equals to req.body. In back-end, we’ll send requests and get responses. req.body is request’s body. After that, we’ll create a variable named data.

In data, we have from, to, subject and html parts. In html, I send token that we created. Data is looks like:

var data = {from: process.env.NODEMAILER_USER,to: email,subject: '',html: `<h1>Hello ${name} ! Please copy token that sent.</h1><h1>${token}</h1>};

Then, we’ll control if user exists with email that given and if it exists we’ll write:

const mailSucces = transporter.sendMail(data, async function (error, info) {}

If there is an error, we’ll return an error. Else, we’ll create an user like this:

const user = await User.create({name,email,password,login: false,point: 0,randomCode: token,id: count,refreshToken});

We’ll define rtoken and create a jwt token in User model. Code is here:

UserSchema.methods.getSignedJwtToken = function () {return jwt.sign({ id: this._id }, process.env.JWT_SECRET, {expiresIn: "30d"})};

ExpiresIn is 30 days, that is token’s destroy time.

We’ll set user’s refreshToken to rtoken, then save user:

const rtoken = user.getSignedJwtToken();user.refreshToken = rtoken;user.save()

And finally, we’ll return a message and rtoken for check.

return res.json({message: "Email Gönderildi",register: true,rtoken});

That’s it, we’ll continue with activating account. Thanks for reading!

--

--