document.replace()

Replace all document fields.

Signature

replace(object: { ttl: Time | Null, *: Any }) => <Document>

Description

The replace() method replaces all fields with object, except for the immutable metadata fields id, coll, and ts. Fields not present in object, except immutable metadata fields, are removed from the document.

Parameters

Parameter Type Required Description

object

Object

Yes

Object with the replacement document fields.

object fields

Name Type Required Description

ttl

Time

Timestamp indicating when to remove the document. When the document is removed, it ceases to exist and temporal queries can’t recover the document.
Default = null, which persists the document indefinitely.

Return value

Type Description

Document

Document with replaced fields.

Examples

Basic

Given the following document:

{
  id: "777",
  coll: Product,
  ts: Time("2099-04-10T16:50:12.850Z"),
  name: "limes",
  description: "Conventional, 16 oz bag",
  price: 2_99,
  stock: 30,
  category: Category("789")
}

Call replace() with a replacement document object:

Product.byId("777")?.replace({
  name: "limes",
  description: "2 ct",
  price: 99,
  stock: 50,
  category: Category.byId("789")
})
{
  id: "777",
  coll: Product,
  ts: Time("2099-04-10T17:54:37.670Z"),
  name: "limes",
  description: "2 ct",
  price: 99,
  stock: 50,
  category: Category("789")
}

Default values

A field definition can set a default field value for documents in a collection:

collection Customer {
  // `name` accepts `String` and `Null` values.
  // If missing, defaults to `unknown`.
  name: String? = "unknown"
  email: String
}

If you don’t provide a value during document replacement, the document uses the default value:

// Replaces a `Customer` document.
Customer.byId("111")?.replace({
  // The `name` field is missing.
  email: "john.doe@example.com"
})
{
  id: "111",
  coll: Customer,
  ts: Time("2099-02-19T14:53:53.940Z"),
  cart: Order("413002506150347264"),
  orders: "hdW...",
  email: "john.doe@example.com",
  // `name` defaulted to `unknown`.
  name: "unknown"
}

If you provide an explicit null value, the field is null. Fields with null values aren’t stored or returned.

Customer.byId("111")?.replace({
  // `name` is an explicit `null`.
  name: null,
  email: "jane.doe@example.com"
})
{
  id: "111",
  coll: Customer,
  ts: Time("2099-02-19T14:53:53.940Z"),
  cart: Order("413002506150347264"),
  orders: "hdW...",
  // `name` is not stored or returned.
  email: "jane.doe@example.com"
}

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!