【问题标题】:Defining a Mongoose Schema on the fly动态定义 Mongoose Schema
【发布时间】:2011-11-21 22:19:34
【问题描述】:

我有一个模型文件,它收集了我所有的 Mongoose 模型。我想用可变数量的字段初始化的模型之一。目前我定义的字段比我认为需要的要多:

TallySchema = new mongoose.Schema
  0: Number
  1: Number
  ...
  20: Number

显然这并不理想。我看到 Mongoose 将允许您在 Schema 定义之外指定选项,但看不到如何添加新字段(或路径,我猜是在 Mongoose 中)。

【问题讨论】:

    标签: mongodb node.js mongoose


    【解决方案1】:

    基于mongoose plugin documentation,您似乎可以这样做:

    schema.add({ field: Number })
    

    【讨论】:

      【解决方案2】:

      这需要验证,但查看源代码应该是可能的:

      在 Schema 构造函数中,它只是将定义对象传递给this.add() (source)。

      然后在Schema.prototype.add (source) 中创建实际路径。

      所以,您似乎需要做的只是:

      // not sure what this looks like in CoffeeScript
      TallySchema.add({ /* new property definition here */ });
      

      【讨论】:

      • 嗨!有一种不那么“hacky”的方式来实现这一点吗?我的意思是,Mongoose 没有可用于声明条件子模式的特殊日期类型或类似的东西?提前致谢。
      【解决方案3】:

      我在Mongoose documentation page找到了这个:

      var ToySchema = new Schema;
      ToySchema.add({ name: 'string', color: 'string', price: 'number' });
      

      【讨论】:

        【解决方案4】:

        您可以使用“混合”类型来封装您的值。虽然不可能让他们处于顶级水平,但否则效果很好。

        new mongoose.Schema({
          average: Number,
          countPerRating: mongoose.Schema.Types.Mixed,
        });
        

        这是一个 mapreduce 模式的摘录。我使用混合类型来存储某人给出某个评分的次数,所以我们可以说“10 个 1 星评分,45 个 4 星评分”等。

        混合类型非常适合。

        【讨论】:

          猜你喜欢
          • 2021-03-22
          • 1970-01-01
          • 2018-03-15
          • 2012-07-14
          • 2014-05-29
          • 2021-09-10
          • 1970-01-01
          • 2015-05-28
          • 2019-10-03
          相关资源
          最近更新 更多