title: check if username and email is unique in database
body: <p>Tried searching the net for 2 days and still could not find a specific answer. I have the below node.js code for user routes and models. How can I check if the username and email has never appear in the MongoDB, and prompt the user a message if there is? </p>
  
  <p>model:</p>
  
  <pre><code>var mongoose = require('mongoose');
  var bcrypt = require('bcryptjs');
  
  // User Schema
  var UserSchema = mongoose.Schema({
    username:{type: String , required:true, index: true, unique:true},
    email:{type: String, required:true, index: true, unique:true},
    password:{type: String, required:true}
  });
  
  module.exports = mongoose.model('User', UserSchema)
  </code></pre>
  
  <p>route:</p>
  
  <pre><code>var express = require('express');
  var router = express.Router();
  var User = require('../models/user');
  var bcrypt = require('bcryptjs');
  
  // Get Homepage
  router.get('/', function(req, res){
      res.render('index');
  });
  
  router.get('/register',function(req,res){
      res.render('register');
  });
  
  // submit form
  router.post('/submit', function(req, res){
  
      // retrieve data from posted HTML form
      var username = req.body.username;
      var email = req.body.email;
      var password = req.body.password;
      var password_confirm = req.body.password_confirm;
  
      // express validator
      req.checkBody('username','Username is required').notEmpty();
      req.checkBody('email','Email is required').notEmpty();
      req.checkBody('email','Invalid email').isEmail();
      req.checkBody('password','Password is required').notEmpty();
      req.checkBody('password','Password must contain at least 6 characters').isLength({min:6});
      req.checkBody('password_confirm','Password mismatch').equals(req.body.password);
  
      // store the errors
      var errors = req.validationErrors();
      if(errors){res.render('register',{errors:errors});}
      else {
          // hash password
          var salt = bcrypt.genSaltSync(10);
          var hash = bcrypt.hashSync(password, salt);
          password=hash;
  
          // load data into model
          var newUser = new User ({username:username, email:email, password:password});
          // save the new user
          newUser.save(function(err,newUser){
              if(err){console.error(err);}
              // console.error is same, but in stderr form
              else{
                  console.log('new user saved successfully');
                  console.log(newUser);
              }
          });
          res.redirect('/');
      }
  });
  
  module.exports = router;
  </code></pre>