I'm using Node.js, express.js, mongoose, and pug. I'm trying to create a registration/signup/login system. The name and email are being stored to mongoose database with schema specified for the name, email and date. The name and email value come from the pug page which sends a post request. I will add other registration details later on in the code, but I'm unable to think about a way to implement email checking.
This is my /routes/index.js
const express = require('express');
const {
check,
validationResult
} = require('express-validator');
const router = express.Router();
//Mongoose
const mongoose = require('mongoose');
var registration = require('../models/registrations') //Important
//Routes
//------------------------------------------------------------------------------------REGISTER/SIGN UP
router.get('/', (req, res) => {
res.render('./home.pug')
})
router.get('/register', (req, res) => {
res.render('register', {
title: 'Register'
});
});
router.post('/register', [
check('name')
.isLength({
min: 5
})
.withMessage('Please enter a name'),
check('email')
.isLength({
min: 14
})
.withMessage('Please enter an email'),
], (req, res) => {
const errors = validationResult(req);
if (errors.isEmpty()) {
const regis = new registration(req.body);
regis.save()
.then(() => {
res.send('Thank you for your registration!');
})
.catch((err) => {
console.log(err);
res.send('Sorry! Something went wrong.');
})
} else {
res.status(422).render('register', {
title: 'Registration form',
errors: errors.array(),
data: req.body,
});
}
console.log(req.body)
})
//Register-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x
//-------------------------------------------------------------------------------------------LOGIN
router.get('/login', (req, res) => {
res.render('login', {
title: 'Login'
});
});
//Login-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x
router.get('/about', (req, res) => {
res.render('about', {
title: 'About'
});
});
module.exports = router;
I have tried using this:
var emailcheck = registration.findOne({email: req.body.email});
if (emailcheck){
//Give error
}else{
//Run this
}
However, it didn't work like I thought it would. Sometimes it gave me an error, sometimes it would run even when the email is already used.