检查用户名和电子邮件在数据库中是否唯一

时间:2017-07-11 14:37:04

标签: mongodb express mongoose

尝试在网上搜索2天仍无法找到具体答案。我有用于用户路由和模型的以下node.js代码。如何检查用户名和电子邮件是否从未出现在MongoDB中,如果有,则提示用户输入消息?

模型:

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)

路线:

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;

1 个答案:

答案 0 :(得分:3)

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
    });

  });
})

您必须捕获错误并将其返回到应用程序的前端。上面的代码应该演示如何使用服务器状态500来实现此目的。关于搜索网络,这个答案和问题与前一个问题非常相似:

  

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

我希望这在某种程度上有所帮助。