5

I'm familiar with variant type of OCaml. For example,

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

I know how to define Number and String in MongoDB, but my question is how to define the variant type as above in MongoDB:

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

Does anyone have any idea?

Edit 1: I just found this answer and this answer. They use classes or functions to mimic variant. It works well in JavaScript in Front-end. However, the question is whether it is possible to put them in a Schema?

SoftTimur
  • 5,630
  • 38
  • 140
  • 292

2 Answers2

1

I think mongoose wants you to use a nested type to declare a property as an object. Using your foo type above:

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

Or - you could punt and use mixed - but that seems really wishy-washy to me.

Or - in the true spirit of oCaml - you can have that var defined using a pattern (type+object):

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

Where varInfo's structure depends on varType. THAT would make your mongo queries eaiser to manage.

Hope that's the direction you were looking for! FYI - I find this simple post really helpful.

bri
  • 2,932
  • 16
  • 17
0

You can use this code see the mongo documentation here 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” ] } 
Amai Mask
  • 1
  • 1
  • Sorry, `$type selects the documents where the value of the field is an instance of the specified BSON type(s)`. `$type` should be used in a query rather than in a schema definition, right? – SoftTimur May 12 '18 at 03:50