Update documents

This tutorial shows how to update select document fields and how to replace the whole document.

Check that an entity exists

Before continuing, it might be helpful to cover a basic error detection method to verify that the object exists before making a query on the object.

For database entities that are assigned an id at creation time, including Documents, you can get the instance using the byId() method on the object. For example, the following query returns a document created in the Query on collections tutorial:

CoffeeBean.byId("378507396792713281")

Try it.

If you make the same query using an invalid id, you get an error response:

CoffeeBean.byId("366190711733747780")
CoffeeBean.byId("366190711733747780") /* not found */

Instead of providing the logic to handle the error response, you can proactively check that the document exists using the exists() method on the document object:

CoffeeBean.byId("366190711733747780").exists()
false

A response of true means the object exists, and a response of false means the object doesn’t exist.

Other database entities that require a name field at creation can be retrieved using the byName() method on the object, and they also, similarly, have an exists() method to test for their existence.

The following continues with making updates to documents, but you can try testing for existence at any time.

Update a field in a document

Documents have IDs that you can use as an alternative to the Set selection methods to reference the document you want. For simplicity, this exercise gets a document directly by referencing its id field.

The id of a document created in the Query on collections tutorial is 378507396792713281. You should have a different id in your dataset because every document has a unique id. Use a document id from your dataset to update the Owner name.

  1. In this example, one of the documents has this Owner name:

    CoffeeBean.byId("378507396792713281") { Owner }
    {
      Owner: "grounds for health admin"
    }

    The document id is passed to the byId() method to get the document you want, and projection is used to get the Owner field in that document.

  2. Use projection with the Document update() method to change the Owner field value:

    CoffeeBean.byId("378507396792713281")!.update(
      { Owner: "Healthy Grounds, Inc." }
    )
    {
      id: "378507396792713281",
      coll: CoffeeBean,
      ts: Time("2023-10-14T18:57:58.550Z"),
      Species: "Arabica",
      Owner: "Healthy Grounds, Inc.",
      Country_of_Origin: "Guatemala",
      Harvest_Year: "",
      Quality_Parameters: {
        Aroma: 8.42,
        Flavor: 8.5,
        Balance: 8.42
      },
      Altitude: {
        unit_of_measurement: "m",
        mean: 1700
      }
    }

    The response shows that Owner is updated while all other fields remain unchanged.

    See non-null assertion postfix to learn more about the ! operator, which you need when static type checking is enabled.

Add a field to a document

  1. In addition to changing a field, you can use the same update()method to add a field.

    Add an Acreage field with a value of 10,000 acres to the first document in the collection. You might want to view the document before adding the field with the CoffeeBean.all().first() query.

    Add the new field:

    CoffeeBean.all().first()!.update({ Acreage: 10000 })
    {
      id: "378484096953745473",
      coll: CoffeeBean,
      ts: Time("2023-10-14T19:03:12.370Z"),
      Species: "Arabica",
      Owner: "metad plc",
      Country_of_Origin: "Ethiopia",
      Harvest_Year: 2014,
      Quality_Parameters: {
        Aroma: 8.67,
        Flavor: 8.83,
        Balance: 8.42
      },
      Altitude: {
        unit_of_measurement: "m",
        mean: 2075
      },
      Acreage: 10000
    }
  2. To delete the same field, restoring the document to its initial state, run the following query, setting the value of the field you want to delete to null:

    CoffeeBean.all().first()!.update({ Acreage: null })

    Verify the result.

Update fields in select documents

You can also use Set methods to select documents you want to update.

This exercise uses the where() method to select the documents above a given Flavor value and applies an anonymous function to each of the selected documents, which adds a Best_of_Class field with the date today.

  1. Select the documents and apply the function:

    CoffeeBean.all()
      .where(.Quality_Parameters.Flavor > 8.5)
      .forEach(bean => {
        bean.update({ Best_of_Class: Date.today() })
    })
  2. View all documents in the collection to see that only the selected documents now have a Best_of_Class field:

    CoffeeBean.all()
    {
      data: [
        {
          id: "378484096953745473",
          coll: CoffeeBean,
          ts: Time("2023-10-14T19:18:33.390Z"),
          Species: "Arabica",
          Owner: "metad plc",
          Country_of_Origin: "Ethiopia",
          Harvest_Year: 2014,
          Quality_Parameters: {
            Aroma: 8.67,
            Flavor: 8.83,
            Balance: 8.42
          },
          Altitude: {
            unit_of_measurement: "m",
            mean: 2075
          },
          Best_of_Class: Date("2023-10-14")
        },
        {
          id: "378507396792713281",
          coll: CoffeeBean,
          ts: Time("2023-10-14T18:57:58.550Z"),
          Species: "Arabica",
          Owner: "Healthy Grounds, Inc.",
          Country_of_Origin: "Guatemala",
          Harvest_Year: "",
          Quality_Parameters: {
            Aroma: 8.42,
            Flavor: 8.5,
            Balance: 8.42
          },
          Altitude: {
            unit_of_measurement: "m",
            mean: 1700
          }
        }
      ]
    }

Replace whole document contents

Use the replace() method to replace the full contents of a document.

  1. This example replaces all fields except the id, coll, and ts metadata fields, which are immutable:

    CoffeeBean.all().first()!.replace(
    {
      Owner: "metad plc",
      Country_of_Origin: "Ethiopia",
    })
    {
      id: "378484096953745473",
      coll: CoffeeBean,
      ts: Time("2023-10-14T19:27:55.770Z"),
      Owner: "metad plc",
      Country_of_Origin: "Ethiopia"
    }
  2. Restore the original document, using the Query on collections tutorial data:

    CoffeeBean.all().first()!.replace(
    {
          Species: "Arabica",
          Owner: "metad plc",
          Country_of_Origin: "Ethiopia",
          Harvest_Year: 2014,
          Quality_Parameters: {
            Aroma: 8.67,
            Flavor: 8.83,
            Balance: 8.42
          },
          Altitude: {
            unit_of_measurement: "m",
            mean: 2075
          }
    })
    {
      id: "378484096953745473",
      coll: CoffeeBean,
      ts: Time("2023-10-14T19:31:10.030Z"),
      Species: "Arabica",
      Owner: "metad plc",
      Country_of_Origin: "Ethiopia",
      Harvest_Year: 2014,
      Quality_Parameters: {
        Aroma: 8.67,
        Flavor: 8.83,
        Balance: 8.42
      },
      Altitude: {
        unit_of_measurement: "m",
        mean: 2075
      }
    }

Is this article helpful? 

Tell Fauna how the article can be improved:
Visit Fauna's forums or email docs@fauna.com

Thank you for your feedback!