将模型参数传递到猫鼬模型中 [英] Passing model parameters into a mongoose model

查看:125
本文介绍了将模型参数传递到猫鼬模型中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

var Example = mongoose.model('Example',userSchema)

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

  //用户json对象由一些中间件
var模型填充= new Example({name:'example',....,userId:req.user._id});

模型的构造函数需要很多参数,这些参数在模式更改时会写入和重构。有没有办法做这样的事情:

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

或者是创建帮助方法来生成JSON对象甚至将userId附加到的最佳方式请求机构?还是有没有想到的方式?

解决方案

  _ = require (下划线)

var model = new示例(_。extend({userId:req.user._id},req.body))
/ pre>

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

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


I have a mongoose model that has an association with a user model e.g.

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

var Example = mongoose.model('Example', userSchema)

When I instantiate a new model I do:

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

The model's constructor takes a lot of parameters which has become tedious to write and refactor when the schema changes. Is there way of doing something like:

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

Or is the best way to create a helper method to generate a JSON object or even attach the userId to the request body? Or is there way that I haven't even thought of?

解决方案

_ = require("underscore")

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

or if you want to copy userId into req.body:

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

这篇关于将模型参数传递到猫鼬模型中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆