2013-02-19 53 views
5

我有一個與用戶模型有關的貓鼬模型。將模型參數傳遞到貓鼬模型

var exampleSchema = mongoose.Schema({ 
    name: String, 
    <some more fields> 
    userId: { type:mongoose.Schema.Types.ObjectId, ref: 'User' } 
}); 

var Example = mongoose.model('Example', userSchema) 

當我實例化一個新的模式,我做的事:

// the user json object is populated by some middleware 
var model = new Example({ name: 'example', .... , userId: req.user._id }); 

該模型的構造函數有很多參數已成爲繁瑣的編寫和重構架構更改時。有沒有做類似的方式:

var model = new Example(req.body, { userId: req.user._id }); 

或者是創建一個輔助方法來生成一個JSON對象,甚至是用戶id附加到請求主體的最好方法?或者我有沒有想過的方式?

回答

7
_ = require("underscore") 

var model = new Example(_.extend({ userId: req.user._id }, req.body)) 

,或者如果你想用戶id複製到req.body:

var model = new Example(_.extend(req.body, { userId: req.user._id })) 
2

如果我理解正確的話,你會想好以下幾點:

// We "copy" the request body to not modify the original one 
var example = Object.create(req.body); 

// Now we add to this the user id 
example.userId = req.user._id; 

// And finally... 
var model = new Example(example); 

而且, 不要忘記添加您的架構選項{ strict: true },否則您可能會保存不需要的/攻擊者的數據。

+4

嚴格默認啓用,因爲貓鼬3. – 2013-02-19 14:08:22

+0

很高興知道,感謝您的提示! – gustavohenke 2013-02-19 14:10:00

+0

'Object.create'在這裏看起來並不合適,因爲它不會複製'req.body',它將它用作原型對象。很確定,Mongoose會忽略原型的屬性。 – JohnnyHK 2013-02-19 14:19:23