Orchestrating multiple dependent expressions in the same transaction with Do

Chris Biscardi
InstructorChris Biscardi
Share this video with your friends

Social Share Links

Send Tweet
Published 5 years ago
Updated 4 years ago

There are a couple of different way to execute multiple expressions in FQL. Do is a function that lets us execute expressions in order and fail the entire query if one of the expressions fails.

Do(
  Create(Collection("products")), {
    data: {
      "name": "Bacon",
      "description": "crispy, hot",
      "price": 4.27,
      "quantity": 1000,
      "warehouse": Ref(Collection("warehouses"), "244075679449088521"),
      "backorderLimit": 15,
      "backordered": false
    }
  }),
  Paginate(Match(Index("all_products")))
)

Instructor: [0:00] The do function in FQL allows us to evaluate a series of expressions in order from left to right. This means we can do insertions. Later, after we've done the insertion, we can query for that ID and get it returned.

[0:14] If any of the expressions in a do call fail, all we get back is an error and none of the insertions are committed. The do function only returns the results of the last statement.

[0:24] In the FaunaDB console in our products collection, we have three documents. We have stock for cups, beef chick, and pizza,. Using the do function, we can create a new product and then return the paginated match on the index of all products.

[0:41] Note that because the do function executes from left to right, the create function will execute first, and the paginate is able to access the results of the create. When we run this query, we can see that we returned four documents in our products collection instead of the three we had before.

[0:59] If we refresh the products collection, we can see that bacon is now inserted into the products collection.