相关疑难解决方法(0)

将模型参数传递到mongoose模型

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

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附加到请求主体的最佳方法?或者有没有我想过的方式?

mongoose mongodb node.js express

7
推荐指数
1
解决办法
9309
查看次数

标签 统计

express ×1

mongodb ×1

mongoose ×1

node.js ×1