2012-11-30 30 views
1

我正在尋找一些創建crud REST api時所做的繁瑣樣板代碼的快捷方式。我正在使用快遞併發佈一個我希望保存的對象。將req.body屬性移動到模型對象的有效方式

app.post('/', function(req, res){ 
    var profile = new Profile(); 

    //this is the tedious code I want to shortcut 

    profile.name = req.body.name; 
    profile.age = req.body.age; 
    ... and another 20 properties ... 

    //end tedious code 

    profile.save() 
}); 

有沒有簡單的方法來將所有req.body屬性應用到配置文件對象?我將編寫相同的粗體代碼以切斷不同的模型,並且在開發過程中,屬性會頻繁更改。

+0

* * for-in *循環怎麼樣。 – xiaoyi

+0

我想我可以只...爲(var我在req.body)如果(obj.hasOwnProperty(i)){..但想知道是否有任何其他隨機絨毛屬性添加到req.body,我應該過濾掉 – MonkeyBonkey

+0

如何將繁瑣的代碼移動到一個函數中,以便只需執行一次?例如profile = GetProfileFromBody(req.body); –

回答

1

怎麼樣換在循環,假設你new Profile()會產生一個好的模式穿上值,這將避免req.body惹您。

for (var key in profile) { 
    if (profile.hasOwnProperty(key) && req.body.hasOwnProperty(key)) 
    profile[key] = req.body[key]; 
} 

更準確地說,對於這種情況,您應該有一個針對每個模塊的解析/字符串化函數。所以,你可以簡單地調用:

var profile = Profile.parse(req.body); 

事實上,如果您正在使用非IE瀏覽器或者node.js中/犀牛打,你的req.body是乾淨,你可以不喜歡它:

var profile = req.body; 
profile.__proto__ = Profile.prototype; 

然後你就完成了。

+0

我想你可能想要檢查'profile .hasOwnProperty(key)'以及/而不是 – Eric

+0

@Eric你是對的,同時檢查 – xiaoyi

0

可以做這樣的事情:

for(key in req.body) { 
    profile[key] = req.body[key]; 
} 
+0

雖然它沒有合理的範圍,但你應該在裏面有一個'var'。 – Eric

+0

確實需要添加我必須過濾掉的任何絨毛或系統屬性。什麼時候需要檢查req.body.hasOwnProperty(key)? – MonkeyBonkey

0

迭代所有密鑰可能是一個壞主意。最好是:

['name', 'age', ...].forEach(function(key) { 
    profile[key] = req.body[key]; 
}); 
相關問題