【问题标题】:Passing model parameters into a mongoose model将模型参数传递给猫鼬模型
【发布时间】:2013-02-04 05:38:43
【问题描述】:

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

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 附加到请求正文的最佳方法?还是有什么我没想到的方法?

【问题讨论】:

    标签: node.js mongodb express mongoose


    【解决方案1】:
    _ = 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 }))
    

    【讨论】:

      【解决方案2】:

      如果我对您的理解正确,您可以尝试以下方法:

      // 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 },否则您可能会保存不需要的/攻击者数据。

      【讨论】:

      • 从 mongoose 3 开始默认启用严格。
      • Object.create 似乎不适合这里,因为它不会复制 req.body,它使用它作为原型对象。很确定 Mongoose 会忽略原型的属性。
      【解决方案3】:

      从 Node 8.3 开始,你也可以使用Object Spread syntax

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

      注意顺序很重要,后面的值会覆盖前面的值。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-04-11
        • 2020-05-29
        • 2011-08-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多