我有一個與用戶模型有關的貓鼬模型。將模型參數傳遞到貓鼬模型
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附加到請求主體的最好方法?或者我有沒有想過的方式?
嚴格默認啓用,因爲貓鼬3. – 2013-02-19 14:08:22
很高興知道,感謝您的提示! – gustavohenke 2013-02-19 14:10:00
'Object.create'在這裏看起來並不合適,因爲它不會複製'req.body',它將它用作原型對象。很確定,Mongoose會忽略原型的屬性。 – JohnnyHK 2013-02-19 14:19:23