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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With