【问题标题】:Define variant type in Mongoose在 Mongoose 中定义变体类型
【发布时间】:2018-10-09 04:32:00
【问题描述】:

我熟悉 variant 类型的 OCaml。例如,

type foo =
    | Int of int
    | Pair of int * string

我知道如何在 MongoDB 中定义 NumberString,但我的问题是如何在 MongoDB 中定义上述变体类型:

var PostSchema = new mongoose.Schema({
    num: { type: Number },
    name: { type: String },
    variant: ???
})

有人知道吗?

编辑 1: 我刚刚找到 this answerthis answer。他们使用类或函数来模仿variant。它在前端的 JavaScript 中运行良好。但是,问题是是否可以将它们放在Schema 中?

【问题讨论】:

    标签: javascript object mongoose ocaml mongoose-schema


    【解决方案1】:

    您可以使用此代码查看这里的 mongo 文档 https://docs.mongodb.com/manual/reference/operator/query/type/

    var PostSchema = new mongoose.Schema({
        num: { type: Number },
        name: { type: String }, 
        variant: { $type: [ Int: “int” , Pair:[“int”, “string” ] } 
    

    【讨论】:

    • 对不起,$type selects the documents where the value of the field is an instance of the specified BSON type(s)$type 应该用在查询而不是模式定义中,对吧?
    【解决方案2】:

    我认为 mongoose 希望您使用嵌套类型将属性声明为对象。使用上面的 foo 类型:

    var PostSchema = new mongoose.Schema({
       num: [Number],
       name: [String],
       variant: {
          fooInt: [Number]
          fooPair: {
             fooInt: [Number],
             fooString: [String]
          }
        }
     });
    

    或者 - 你可以使用mixed - 但这对我来说似乎真的很虚张声势。

    或者 - 本着 oCaml 的真正精神 - 您可以使用模式(类型+对象)定义该 var:

     ...
     variant: {
        varType: [Number],
        varInfo: [Mixed]
     }
    

    varInfo 的结构取决于 varType。这将使您的 mongo 查询更易于管理。

    希望这就是您要寻找的方向!仅供参考 - 我发现 this simple post 真的很有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-11
      • 1970-01-01
      • 2019-07-31
      • 1970-01-01
      • 2019-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多