我有一个猫鼬模型与用户模型有关联,例如
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对象甚至将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 }))