2016-10-20 8 views
0

特定のルートのフィールドをフィルタリングする良い方法は何ですか?req内のフィールドをフィルタリングするための適切な方法

私はこのエンドポイントAのためのミドルウェアおよびBを作ることを考えていた:

module.exports.filterA = function (req, res, next) { 

// filter out unwanted fields for A in req.body  
    next(); 
}; 


module.exports.filterB = function (req, res, next) { 

// filter out unwanted fields for B in req.body 

    next(); 
}; 

エンドポイントAとBが唯一自分の特定のフィールド

router.post('/A', filterA, saveReqBodyToDatabase); 
router.post('/B', filterB, saveReqBodyToDatabase); 
に聞かせて確認するために、次のようにその後、私は、フィルタを使用することができます

私の戦略は、req.bodyで望ましくないものをすべて切り取って、最終的にデータベース全体に要求を保存し、各ルートに特定の保存方法を書かないようにすることです...

答えて

0

あなたは

module.exports.filterA = function (req, res, next) { 
    delete req.body.unwantedField1; 
    delete req.body.unwantedField2; 
    delete req.body.unwantedField3; 
// filter out unwanted fields for A in req.body  
    next(); 
}; 

を使用するかは、1つまたは2つのフィールドを保持していないし、残りを削除する場合:

module.exports.filterA = function (req, res, next) { 
    var reqBodyOfOnlyDesiredAttributes = { 
     attr1 : req.body.attr1, 
     attr2 : req.body.attr2, 
     attr3 : req.body.attr3 
    } 
    req.body = reqBodyOfOnlyDesiredAttributes; 
    next(); 
}; 
+0

は良い、私は唯一の特定のフィールドを維持したい、残り – Lev

+0

缶を削除します私が書いた2番目のコードスニペットを試してみてください。 – ardilgulez

関連する問題