title: Nodejs: validate if email already exists in the database when registering user
body: <p>I've tried some methods but nothing works
  and I'm trying to change</p>
  <p>Anyone can give me a little trick to create this function in node js?</p>
  <p>Your suggestions will be very helpful for me to solve it</p>
  <pre class="lang-js prettyprint-override"><code>//router_register.js
  // Definisikan router dari express
  const router = require('express').Router();
  // Ambil index.js dari controller dan panggil variabel didalamnya
  const registerController = require('../controllers').register;
  // Definisikan middleware verify.js
  const verifyUser = require('../configs/verify');
  
  // Rute 'http://localhost:5050/register/' digunakan untuk menampilkan form register
  router.get('/', verifyUser.isLogout, registerController.formRegister);
  // Rute 'http://localhost:5050/register/save' digunakan untuk menyimpan data yang diinput user saat register
  router.post('/save', verifyUser.isLogout, registerController.saveRegister);
  
  // Export agar dapat dibaca oleh express
  module.exports = router;
  </code></pre>
  <pre class="lang-js prettyprint-override"><code>//controller_register
  const config = require('../configs/database');
  let mysql = require('mysql');
  let pool = mysql.createPool(config);
  
  pool.on('error', (err)=&gt; {
    console.error(err);
  });
  
  module.exports = {
    formRegister(req, res) {
      res.render(&quot;login&quot;, {
        // Definisikan semua varibel yang ingin ikut dirender kedalam register.ejs
        url: 'http://localhost:5050/',
      });
    },
    saveRegister(req, res) {
      let username = req.body.username;
      let email = req.body.email;
      let password = req.body.pass;
  
      if (username &amp;&amp; email &amp;&amp; password) {
        pool.getConnection(function(err, connection) {
          if (err) throw err;
          connection.query(
            `INSERT INTO table_user (user_name, user_email, user_password) VALUES (?,?,SHA2(?,512)); `, [username, email, password], function (error, results) {
              if (error) throw error;
              req.flash('color', 'success');
              req.flash('status', 'Yes..');
              req.flash('message', 'Registrasi berhasil');
              res.redirect('/login');
            });
          connection.release();
        })
      } else {
        res.redirect('/login');
        res.end();
      }
    }
  }
  </code></pre>
  <p>And please tell me which parts I should fix to make it even better for this coding</p>