将模型parameter passing给mongoose模型

我有一个与用户模型有关联的mongoose模型

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 }); 

或者是创build一个帮助器方法来生成一个JSON对象,甚至附加userId到请求正文的最好方法? 还是有没有想过的方法呢?

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

或者如果你想将userId复制到req.body:

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

如果我正确地理解了你,你会很好的尝试以下几点:

 // 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 } ,否则您可能会保存不需要的/攻击者的数据。