簡體   English   中英

如何檢查使用電子郵件的用戶是否已經存在?

[英]How to check if user with email already exists?

我試圖阻止使用以前注冊的電子郵件進行注冊。 我試圖在貓鼬模式中創建自定義驗證。 但它給了我一個錯誤ValidationError:用戶驗證在MongooseError.ValidationError失敗 代碼如下。 有人可以告訴我錯誤在哪里,或者是檢查用戶電子郵件是否存在於db中的更好方法。

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

檢查電子郵件ID是否已存在於數據庫中的最佳方法是使用express-validator。 從那以后,升級到版本4,API發生了變化。 現在,不要使用:

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

..在您的app.js文件中,然后調用中間件。 相反,只需在您的用戶路由文件中執行此操作即可:-

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

現在,要檢查數據庫中是否已存在電子郵件ID,您將必須使用Promise。 這是一個工作代碼:

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

您也可以類似地執行此操作以檢查用戶名。 這是express-validator的官方GitHub頁面的鏈接

您可以使用email-check程序包來檢查用戶之前是否已經注冊( email字段中是否有重復的電子郵件地址)。
這是下載軟件包https://www.npmjs.com/package/email-check的鏈接

通過在模型內部編寫unique: true屬性,將提供不重復的郵件地址。 但是您還應該包括可以在Router內執行的email-chack驗證的驗證

import emailCheck from "email-check";
//other imports

router.post("/register", (req, res) => {
    var name = req.body.name;
    var email = req.body.email;
    var password = req.body.password;
    var confirmedPassword = req.body.confirmedPassword;

    // your validation for another fields
    emailCheck(email)
        .then(() => {
            User.create(req.body)
                .then(() => {
                    res.send(req.body);
                })
                .catch((error) =>
                    res.json({serverErrorDublicateEmail: "The email address is already subscribed. Please try to use another one or simply Log in"});
                });
        })
        .catch(() => {
            res.json({serverErrorEmailExistence: "The email address doesn't exist. Please try the valid one"});
        });
});

emailCheck返回一個Promise 注意:我正在使用ES6語法。

就這樣。 您的UserSchema可以保留而無需任何驗證。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM