Reputation: 5230
I am using mongoose.js with node.js. I have a mongoose schema as shown below.
myModel: {
type: Schema.Types.Mixed,
}
I want to restrict the values in the schema to predefined values of type
String
where as my keys should be dynamic.
For example,
myModel: {
"Dynamic Key 1" : "Restricted value 1",
"Dynamic Key 2" : "Restricted value 2",
"Dynamic Key 3" : "Restricted value 3"
}
where my values must accept Restricted value 1
, Restricted value 2
and Restricted value 3
only allowing keys to accept anything without any restrictions.
Is Schema.Types.Mixed the right type to be used here? If not, what is the best approach?
Upvotes: 1
Views: 692
Reputation: 311835
It's best to avoid dynamic keys if possible as they make everything harder. Instead of using Mixed
, give the field more structure by making myModel
an array that contains a dynamic key
value and a string value
field that's validated using enum
:
myModel: [{
key: String,
value: {
type: String,
enum: ['Restricted value 1', 'Restricted value 2', 'Restricted value 3']
}
}]
Your example doc would become:
myModel: [
{ key: "Dynamic Key 1", value: "Restricted value 1" },
{ key: "Dynamic Key 2", value: "Restricted value 2" },
{ key: "Dynamic Key 3", value: "Restricted value 3" }
]
Upvotes: 4