简体   繁体   中英

Can you query the DB inside a validate_doc_update function?

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 (eg 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?

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 eg 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.

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