Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
716 views
in Technique[技术] by (71.8m points)

node.js - Passing model parameters into a mongoose model

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
_ = 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 }))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...