2013-02-19 97 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