2017-07-11 67 views
1

嘗試搜索網絡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; 

回答

2
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?

我希望這有助於在一定程度上。

+0

感謝您的回覆。但我仍然可以用相同的用戶名成功保存新條目到mongodb中。當我使用console.log(err)時,它不會產生任何錯誤。我檢查了您提供的另一個案例的鏈接,至少發現了該案例的錯誤消息。你知道我爲什麼沒有犯錯嗎? – unclegood

+0

,因爲您可能沒有以相同的方式定義變量。在這裏,我看到你正在使用'var errors = req.validationErrors();'嘗試控制檯記錄'錯誤'並查看實際出現的內容。 – ZombieChowder

相關問題