2017-02-22 113 views
0

我正試圖阻止以前註冊的電子郵件註冊。我試圖在貓鼬模式中創建一個自定義驗證。但它給了我一個錯誤ValidationError:用戶驗證失敗 在MongooseError.ValidationError。代碼在下面。有人可以告訴我錯誤在哪裏,或者更好的方法來檢查用戶電子郵件是否存在於數據庫中。如何檢查使用電子郵件的用戶是否已經存在?

// user schema 
var UserSchema = mongoose.Schema({ 
    username: { 
     type: String, 
     index: true, 
     require: true 
    }, 
    password: { 
     type: String, 
     require: true 
    }, 
    email: { 
     type: String, 
     lowercase: true, 
     trim: true, 
     index: { 
      unique: true, 
     }, 
     validate: { 
      validator : isEmailExists, msg: 'Email already exists' 
     } 
    }, 
    name: { 
     type: String 
    }, 
    admin: Boolean, 
    active: Boolean, 
}); 

// validation 
function isEmailExists(email, callback) { 
    if (email) { 
     mongoose.models['User'].count({ _id: { '$ne': this._id }, email: email }, function (err, result) { 
      if (err) { 
       return callback(err); 
      } 
      callback(!result); 
     }) 
    } 
} 
// createUser function 
module.exports.createUser = function(newUser, callback){ 
    bcrypt.genSalt(10, function(err, salt) { 
     bcrypt.hash(newUser.password, salt, function(err, hash) { 
      newUser.password = hash; 
      newUser.save(callback); 
     }); 
    }); 
} 

路由器

router.post('/register', function(req, res, next) { 
    var name = req.body.name; 
    var email = req.body.email; 
    var password = req.body.password; 
    var confirmedPassword = req.body.confirmedPassword; 

    // Validation 
    req.checkBody('name', 'Name is required').notEmpty(); 
    req.checkBody('email', 'Email is required').notEmpty(); 
    req.checkBody('email', 'Email is not valid').isEmail(); 
    req.checkBody('password', 'Password is required').notEmpty(); 
    req.checkBody('confirmedPassword', 'Passwords do not match').equals(req.body.password); 

    var errors = req.validationErrors(); 

    if (errors) { 
     res.render('register', { 
      errors: errors 
     }); 
    } else { 
     var newUser = new User({ 
      name: name, 
      email: email, 
      password: password, 
      admin: false, 
      active: false 
     }); 

     User.createUser(newUser, function (err, user) { 
      if (err) { 
       throw err; 
      } 
     }); 

     req.flash('success_msg', 'You are registerd and can now login'); 
     res.redirect('/users/login'); 
    } 
+0

保存功能在哪裏? – digit

+0

我昨天回答了一個類似的問題。看看:http://stackoverflow.com/questions/42362970/insert-document-only-if-not-already-exists/42363555#42363555 –

回答

1

檢查電子郵件ID已經在數據庫中使用明文驗證器的存在與否是最好的方式。 由於升級到版本4,API已更改。 現在,而不是使用: -

const expressValidator = require('express-validator'); 

..in你app.js文件,然後調用中間件。相反,只是這樣做在你的用戶路由文件: -

const { check, validationResult } = require('express-validator/check'); 

現在,檢查電子郵件ID在數據庫中已經存在,你將不得不使用承諾。這裏是一個工作代碼: -

 router.post('/register', [ 
      check('name') 
      .not() 
      .isEmpty() 
      .withMessage('Name is required'), 
      check('email') 
      .not() 
      .isEmpty() 
      .withMessage('Email is required') 
      .isEmail() 
      .withMessage('Invalid Email') 
      .custom((value, {req}) => { 
      return new Promise((resolve, reject) => { 
       User.findOne({email:req.body.email}, function(err, user){ 
       if(err) { 
        reject(new Error('Server Error')) 
       } 
       if(Boolean(user)) { 
        reject(new Error('E-mail already in use')) 
       } 
       resolve(true) 
       }); 
      }); 
      }), 
      // Check Password 
      check('password') 
      .not() 
      .isEmpty() 
      .withMessage('Password is required'), 
      // Check Password Confirmation 
      check('confirmedPassword', 'Passwords do not match') 
      .exists() 
      .custom((value, { req }) => value === req.body.password) 
     ], function(req, res) { 
      var name = req.body.name; 
      var email = req.body.email; 
      var password = req.body.password; 
      var confirmedPassword = req.body.confirmedPassword; 

      // Check for Errors 
      const validationErrors = validationResult(req); 
      let errors = []; 
      if(!validationErrors.isEmpty()) { 
      Object.keys(validationErrors.mapped()).forEach(field => { 
       errors.push(validationErrors.mapped()[field]['msg']); 
      }); 
      } 

      if(errors.length){ 
      res.render('register',{ 
       errors:errors 
      }); 
      } else { 
      var newUser = new User({ 
       name: name, 
       email: email, 
       password: password, 
       admin: false, 
       active: false 
      }); 

      User.createUser(newUser, function (err, user) { 
       if (err) { 
       throw err; 
       } 
      }); 

      req.flash('success_msg', 'You are registerd and can now login'); 
      res.redirect('/users/login'); 
      } 

你可以同樣做這個檢查用戶名也。 Here is the link to the official GitHub page of express-validator

相關問題