Search code examples
faunadb

How can I query data from FaunaDb if only some collections have a specific property which I need to filter out


I'm really new to FaunaDb, and I currently have a collection of Users and an Index from that collection: (users_waitlist) that has fewer fields. When a new User is created, the "waitlist_meta" property is an empty array initially, and when that User gets updated to join the waitlist, a new field is added to the User's waitlist_meta array. Now, I'm trying to get only the collections that contain the added item to the waitlist_meta array (which by the way, is a ref to another index (products)). In a other words: if the array contains items, then return the collection/index How can I achieve this? By running this query:

Paginate(Match(Index('users_waitlist')))

Obviously, I'm still getting all collections with the empty array (waitlist_meta: [])

Thanks in advance


Solution

  • you need to add terms to your index, which are explained briefly here.

    the way I find it useful to conceptualise this is that when you add terms to an index, it's partitioned into separate buckets so that later when you match that index with a specific term, the results from that particular bucket are returned.

    it's a slightly more complicated case here because you need to transform your actual field (the actual value of waitlist_meta) into something else (is waitlist_meta defined or not?) - in fauna this is called a binding. you need something along the lines of:

    CreateIndex({
      "name": "users_by_is_on_waitlist",
      "source": [{
        "collection": Collection("users"),
        "fields": {
          "isOnWaitlist": Query(Lambda("doc", ContainsPath(["data", "waitlist_meta"], Var("doc"))))
        }
      }],
      "terms": [{
        "binding": "isOnWaitlist"
      }]
    })
    

    what this binding does is run a Lambda for each document in the collection to compute a property based on the document's fields, in our case here it's isOnWaitlist, which is defined by whether or not the document contains the field waitlist_meta. we then add this binding as a term to the index, meaning we can later query the index with:

    Paginate(Match("users_by_is_on_waitlist", true))

    where true here is the single term for our index (it could be an array if our index had multiple terms). this query should now return all the users that have been added to the waitlist!