I have a collection “user_subscription” that has fields referencing properties from a master collection “subscription_plans” and “pro_user_profile” for “subscription_plan_id” and “user_id” respectively.
Aong with the regualr validation schema of defining required fields and properties I would like to add a way to dynamically validate against the master collection in terms of only accepting document/data only if the said IDs are available in the master collections.
I have found an approach of running the following code in Mongo DB shell (currently working on Mongo Compass) - code below
"db.runCommand({
collMod: ""user_subscription"",
validator: {
$expr: {
$and: [
{
$in: [
""$subscription_plan_id"",
db.getCollection(""subscription_plans"").distinct(""subscription_plan_id"")
]
},
{
$in: [
""$user_id"",
db.getCollection(""pro_user_profile"").distinct(""user_id"")
]
}
]
}
},
validationLevel: ""strict"",
validationAction: ""error""
});"
Now the issue is that this code would keep pulling ID data from the master collections and display them in the validation JSON Schema picture below
Now here is where it wont make sense if there are a million records and this keeps getting updated to the validation schema making it large and growing/updating all the time.
My question is that, is there any way we can dynamically reference the fields and their properties from master collections so that they can be validated in the child collections (example: such as ensuring ID value exists)