2017-01-16 12 views
0

私はすべてのルートの検証としてルートを作成しました。これは私のすべてのリクエストを処理して検証したいのですが、問題は属性がリクエストに含まれているかどうかをチェックしたいだけです。属性は、ユーザーが電子メールを持っていると言うことができますが、他の人はそうではありません、私はボディがこの電子メールを検証する特定のコードを実行する電子メール属性を持っているかどうかをチェックしたいと思います。nodejs express mongoose mongodb

req.body.email; 

が体内にある場合どのように私は知っていますか?

var express = require('express'); 
var router = express.Router(); 


router.use('/', function(req, res, next) { 
      var record = req.body.record, 
       email = record.email, 
       phone_number = record.phone_number, 
       school_id = req.body.schoolId; 

      console.log("validator"); 

      if (record) { 

       if (what is the condition here to check 
        if the body has email) 

        req.asyncValidationErrors() 
        .then(function() { 
         next(); 

        }).catch(function(errors) { 
         if (errors) { 
          res.json({ 
           status: "error", 
           message: "please make sure your data is correct and your email and phone number are not valid" 
          }); 
          return; 
         } 
        }); 
      }); 


     module.exports = router; 

答えて

0

emailが体内にあるかどうかを知るために、あなたはundefinedをチェックする必要があります。身体にない属性は、アクセス時にundefinedを与えます。

if (body.email === undefined) { 
    console.log('email attribute is not in the body, hence it comes here'); 
    return res.json({ 
     status: "error", 
     message: "please make sure your data is correct and your email is valid" 
    }); 
} 

アプリにロダッシュがある場合は、

let _ = require('lodash'); 

let body = req.body; 

if(_.isUndefined(body.email)) { 
    console.log('email attribute is not in the body, hence it comes here'); 
    return res.json({ 
     status: "error", 
     message: "please make sure your data is correct and your email is valid" 
    }); 
} 
+0

それがないとき、これはだけでなく、body.emailのすべてfalsy(https://developer.mozilla.org/de/docs/Glossary/Falsy)の値にブロックを実行します。 – Florian

+0

@Florianはい。あなたが正しい。それを指摘してくれてありがとう。私は更新しました。 – Sridhar

+1

私はロダッシュがここで過度に過剰だと思うのですが、どうしてでしょうか(body.email === undefined)? isUndefinedのソースを参照してください:https://github.com/lodash/lodash/blob/4.17.4/lodash.js#L12212 – DevDig

関連する問題