Computed Fields

THIS PAGE
In the graph
In the CMS
In the API

Computed type fields as the name suggests, are fields that are computed everytime you request them. In the background, there is a function (that you define) that runs, computes and returns the values of the field.

Create a computed field by simply creating a new field and marking the input type as Computed.

In the graph

Screenshot

Things to keep in mind:

  • A Computed field always returns an object
  • You can't directly set a value to these type of fields.

Configuration

To configure a computed filed you have to define two things:

  1. Define what the output of the object will look like.
  2. The function that is used to compute the output of the field.

Let's take an example to understand the configurations. Suppose you have a movies table with a linked field to another table called ratings that stores the list of all the entries of the ratings provided by users to a particular movie.

Now, when you fetch a particular movie you also want to get the averate rating for it to show it on your frontend, rather than querying the the ratings table with another API call and returning the average ratings. You can use a computed field to do it:

I) Define the output

You define if the output of your computed field will be a an object (standalone) or an array of objects (list). In our case we want to return an single object which will be Standalone with a key avgRating.

We'll mark the key as required as we want it to be present at all cases. Under a different use-case or circumstances we can have multiple keys that are being returned but not always be required.

Screenshot

II) Define the computation fuction

Head over to the CODE tab of the computed field. You'll see an empty function over there:

Screenshot

You can modify this function and write your business logic as to what this funtion should do and return at the end. We want to query our ratings table to get all the ratings for the movie and then return the average ratings.

The data parameter always has the complete object of the table to which the computed field it's linked to.

In our case the data parameter will contain the movie object. The code for fetching the ratings and returing the avg will look like this:

module.exports = async function averageRatings({ data }) {
  const allRatings = await Rating.find({ movie: data._id }, "rate")
  const sum = allRatings.reduce((a, b) => ({ rate: a.rate + b.rate }))
  return { avgRatings: sum.rate / allRatings.length }
}

Testing your Computed Fields Response

You can also test your code by clicking the play button in the center.

Screenshot

In the CMS

Screenshot

When you publish a computed field, it's available in the Content Management System. The value of the field is calculated and displayed there.

You can't set the value of the computed field directly since as the name suggests, it's computed!

In the API

In the API the output response for this field is an object or an array of objects as per defined in the graph.

Sample GraphQL Request

query {
  movies {
    name
    _id
    description
    # Marked as a Computed Field
    averageRatings {
      avgRatings
    }
  }
}

Sample GraphQL Response

{
  "data": {
    "movies": [
      {
        "name": "Avengers: Endgame",
        "_id": "60aadf4eeb43e40009bc2eb7",
        "description": "<p>After Thanos, an intergalactic warlord, disintegrates half of the universe, the Avengers must reunite and assemble again to reinvigorate their trounced allies and restore balance.</p>",
        "averageRatings": {
          "avgRatings": 8.5
        }
      }
    ]
  }
Did you find what you were looking for?
👍
👎
What went wrong?
Need more help?We have a thriving Discordcommunity that can help you with all things Canonic. →