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

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

问题描述

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

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

或者是创建辅助方法以生成 JSON 对象甚至将 userId 附加到请求正文的最佳方法?或者有没有我没想到的方法?

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

或者如果您想将 userId 复制到 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天全站免登陆