1

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?

model:

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)

route:

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;
unclegood
  • 277
  • 5
  • 14

1 Answers1

4
app.post('/authenticate', function(req, res) {
  var user = new User({
    username: req.body.username
  });

  user.save(function(err) {
    if (err) {
      if (err.name === 'MongoError' && err.code === 11000) {
        // Duplicate username
        return res.status(500).send({ succes: false, message: 'User already exist!' });
      }

      // Some other error
      return res.status(500).send(err);
    }

    res.json({
      success: true
    });

  });
})

You have to catch the error and return it to the front end of your application. This code above should demonstrate how to achieve this by using server status 500. Regarding searching the web, this answer and question are quite similar to this previous question:

How to catch the error when inserting a MongoDB document which violates an unique index?

I hope this helped to some extend.

ZombieChowder
  • 1,187
  • 12
  • 36
  • thanks for the reply. but I can still save new entries with same username successfully into mongodb. when I use console.log(err), it does not produce any errors. I checked the link of another case you provided, at least there was error message for that case. do you know why I do not have anything in err? – unclegood Jul 11 '17 at 14:58
  • because you might have not defined variables the same way. Here I see you are using this `var errors = req.validationErrors();` try console logging `errors` and see what actually comes up. – ZombieChowder Jul 11 '17 at 15:07
  • Is there anyway to differentiate the error for username compared to email? Because I am pretty sure the err.name and err.code remain the same between the two. The reason I am curious is because I would like to let the user know which of the two is already in use instead of having to guess if its the email or username – Jake May 29 '19 at 05:06
  • @Jake Hello and sorry for the late response. Check the specific **MongoDB error codes** for this. Alternative way of doing it is by creating a **find** query and search for a duplicate. – ZombieChowder Jun 06 '19 at 11:55