简体   繁体   中英

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 ?

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.

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” ] } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM