将模型参数传递到mongoose模型

Cli*_*ive 7 mongoose mongodb node.js express

我有一个猫鼬模型,它与用户模型有关联,例如

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

var Example = mongoose.model('Example', userSchema)
Run Code Online (Sandbox Code Playgroud)

当我实例化一个新模型时,我做了:

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

模型的构造函数需要很多参数,这些参数在模式更改时编写和重构变得冗长乏味.有没有办法做这样的事情:

var model = new Example(req.body, { userId: req.user._id });
Run Code Online (Sandbox Code Playgroud)

或者是创建帮助器方法以生成JSON对象甚至将userId附加到请求主体的最佳方法?或者有没有我想过的方式?

Jea*_*erc 7

_ = require("underscore")

var model = new Example(_.extend({ userId: req.user._id }, req.body))
Run Code Online (Sandbox Code Playgroud)

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

var model = new Example(_.extend(req.body, { userId: req.user._id }))
Run Code Online (Sandbox Code Playgroud)