Reputation: 101
I am using validate_doc_update functions to do basic validation on the object to be stored. This is great to ensure that certain fields are present for example. But is there a way to do a validation based on a query from within the validate_doc_update function? For example, I want people to be able to sign up to bring items to a potluck. So each object will have fields for name, phone, and food (e.g. soda, salad, chips). So my validation function will check for each of those fields. No problem. But I also want to make sure that no more than two people sign up for the same food (not just a basic unique constraint). So if a new object with food value "chips" is being validated, and there are already 2 objects with food value "chips" in the DB, the validation should fail. Is there a way to do this with validation docs?
Upvotes: 0
Views: 67
Reputation: 4953
There is no facility to run a query in validate_doc_update.
One way to solve this issue is to decouple food items from user documents; instead have a document that represents the potluck:
{
_id: "potluck",
chips: {
needed: 2,
providers: ["user_id_1"]
},
soda: {
needed: 5,
providers: ["user_id_2","user_id_3"]
}
}
Here it is quite easy to validate sign ups of items. This document exudes a lot of information e.g. the number of items needed for any item is always needed - providers.length
. User id's link food items users have signed up to provide.
It would be easy to generate a potluck report using a view or two with this approach.
Upvotes: 1