Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define variant type in Mongoose

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?

like image 353
SoftTimur Avatar asked Nov 08 '22 07:11

SoftTimur


1 Answers

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.

like image 139
bri Avatar answered Nov 15 '22 11:11

bri