2015-07-20 65 views
0

在通過MEAN堆棧教程時,我發現自己對以下貓鼬驗證碼感到困惑。模式驗證函數如何在貓鼬中工作?

用戶service.js

exports.findUser = function(email, next){ 
    User.findOne({email:email.toLowerCase()}, function(err,user){ 
     next(err, user); 
    }) 
}; 

user.js的

var userService = require('../services/user-service'); 

var userSchema = new Schema({ 
    ... 
    email:  {type: String, required: 'Please enter your email'}, 
    ... 
}); 

userSchema.path('email') 
    .validate(function(value,next){ 
     userService.findUser(value, function(err, user){ 
      if(err){ 
       console.log(err); 
       return next(false); 
      } 
      next(!user); 
     }); 
    }, 'That email is already in use'); 
  1. 每當userSchema以任何方式訪問時,userSchema.path('email').validate火災和驗證電子郵件字符串。這個驗證也可以在userSchema對象中完成,除非它非常混亂。

  2. in .validate(function(value, next)...value是電子郵件字符串,並且next什麼也沒有給出,並且是未定義的。 (對吧?)

  3. 如果是這樣,那麼我看不到return next(false)next(!user)可以工作。

  4. 我在其他情況下熟悉next,但next在這裏做什麼?

回答

1

下面是它如何工作的:

userSchema.path('email').validate(function (email, next) { 
    // look for a user with a given email 
    // note how I changed `value` to `email` 
    userService.findUser(email, function (err, user) { 
     // if there was an error in finding this user 
     if (err) { 
      console.log(err) 
      // call next and pass along false to indicate an error 
      return next(false) 
     } 
     // otherwise, call next with whether or not there is a user 
     // `user === null` -> then `!user === true` 
     // `user === { someObject }` -> then `!user === false` 
     return next(!user) 
    }) 
    // error message 
}, 'That email is already in use') 

當您點附和:

  1. 是,此功能驗證電子郵件路徑。
  2. 是的,value是電子郵件,所以使用更好的變量命名並將其稱爲email而不是value; next就是這樣:一個函數說「繼續下一步」。
  3. 請參閱上面代碼中的註釋。但是,tldr:如果存在該電子郵件的用戶,則!userfalse;如果用戶不存在,!usertrue。如果next傳遞了false-y值,則認爲存在錯誤。一個真實的價值意味着一切都很好。
  4. 它稱之爲「下一步」。例如

    app.get('/admin*', function (req, res, next) { 
        req.status = 'I was here!' 
        next() 
    }) 
    
    app.get('/admin/users/view', function (req, res, next) { 
        console.log(req.status) // ==> 'I was here!' 
        res.render('admin/users/view.jade', { someLocals }) 
    }) 
    
+0

感謝您的回答。它使得某些事情更加清晰 - 但我的代碼中的「接下來」似乎仍然沒有意義。爲什麼不自己返回'false'或'!user'?那些簡單的布爾人是否不足以作爲'驗證'來完成工作的答案? – dwilbank

+0

,在你的例子中#4 ...「下一步」被定義爲'在頁面上寫下的任何代碼'?這是我混亂的根源。在我的代碼中,沒有預定的「下一個」任務要做。 – dwilbank

+0

「下一步」可能只是「一切都好嗎?」如果沒有,則會拋出錯誤「'該電子郵件已被使用」。此外,你可以'返回false',因爲代碼是異步的。如果返回false,它只會將值返回給lambda函數'function(err,user){/ * etc * /}',而不是驗證函數。 – royhowie