Javascript node.js中post请求的筛选器正文

Javascript node.js中post请求的筛选器正文,javascript,node.js,api,security,express,Javascript,Node.js,Api,Security,Express,有没有办法简化node.js+express中的代码 // Backend handler to register a new participant app.post('/api/participant', function (req, res, next) { // I'm catching the registration form from the request var data = req.body; // I want to make sure the

有没有办法简化node.js+express中的代码

// Backend handler to register a new participant

app.post('/api/participant', function (req, res, next) {
    // I'm catching the registration form from the request
    var data = req.body;

    // I want to make sure the user is not uploading data other
    // than the fields in the form
    var participant = new Participant({
        first: data.first,
        last: data.last,
        email: data.email,
        category: data.category
    });
    participant.save(...);
});
我没有这样做:

    var participant = new Participant(data);
因为任何人都可以(例如)在数据对象中包含
score
属性,并以优势开始竞争


所以我的问题是:我必须在每个帖子处理程序中都这样做,还是有一种过滤属性的方法?

快速的谷歌搜索没有找到任何预先存在的库,但是这个函数应该可以很好地完成这一任务:

function filterKeys(object, keys) {
    Object.keys(object).forEach(function(key) {
        if(keys.indexOf(key) == -1) {
            delete object[key];
        }
    });
}
例如,

var foo = {"foo": 1, "bar": 2, "baz": 3};
console.log(foo); // {"foo": 1, "bar": 2, "baz": 3}
filterKeys(foo, ["foo", "baz"]);
console.log(foo); // {"foo": 1, "baz": 3}
所以在你的情况下

filterKeys(data, ["first", "last", "email", "category"]);

杰出的谢谢:)