我有一个与用户模型关联的mongoose模型,例如
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附加到请求体的最佳方式是什么?或者有没有什么我根本没想过的方法?
发布于 2013-02-19 22:04:01
_ = 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 }))发布于 2013-02-19 22:04:17
如果我没理解错的话,你最好尝试一下下面的方法:
// We "copy" the request body to not modify the original one
var example = Object.create( req.body );
// Now we add to this the user id
example.userId = req.user._id;
// And finally...
var model = new Example( example );此外,不要忘记在您的模式选项中添加 { strict: true },否则您可能会保存不需要的/攻击者的数据。
发布于 2020-09-22 06:10:03
从Node8.3开始,您还可以使用Object Spread syntax。
var model = new Example({ ...req.body, userId: req.user._id });请注意,顺序很重要,后面的值会覆盖前面的值。
https://stackoverflow.com/questions/14959199
复制相似问题