为什么我的中间件不检查电子邮件是否已经存在?

我使用passportJS来validation人员。 我最近意识到的问题是,用户可以注册多个帐户。 我创build了一个中间件来检查电子邮件是否已经被使用,但不知何故仍然通过testing。

var User = require('../models/users'); var authMethods = {}; authMethods.isInUse = function(req,res,next){ User.findOne({"email" : req.body.email}, (err,user) => { if(user){ req.flash('error',"This mail is already in use."); res.redirect('/register'); }else { return next(); } }); } module.exports = authMethods; 

在我的身份validation页面中,我正在调用路由中的中间件以满足条件。

 router.post('/register',authMethods.isInUse ,multipart(),function(req, res) { var image = fs.readFileSync(req.files.image.path); var profilePic = {data : image, contentType : 'image/png'}; var user = new User({ username: req.body.username, email: req.body.email, password: req.body.password, occupation: req.body.occupation, phone: req.body.phone, profilePic : profilePic, firstName : req.body.firstName, lastName : req.body.lastName }); user.save(function(err) { req.logIn(user, function(err) { req.flash("success", "Welcome to the site " + user.username); res.redirect('/flats'); }); }); }); 

我一直无法发现导致问题的错误方法。

如果multipart()做了我认为它的工作(将请求数据parsing为req.body ),那么req.body可能不会在中间件中填充,因为它在多部分中间件之前被调用。

尝试切换中间件function:

 router.post('/register', multipart(), authMethods.isInUse, function(req, res) { ... });