document.replace()
| Learn: Documents |
|---|
Replace all fields in a collection document.
Description
Replaces all fields in an collection document with fields from a provided data
object. Fields not present in the data object, excluding the id, coll, ts,
and data metadata fields, are removed.
Reserved fields
You can’t use this method to insert or edit the following metadata fields:
-
id -
coll -
ts -
data
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
data |
true |
Fields for the collection document. Fields not present in the object,
excluding the The object can’t include the following metadata fields:
|
Return value
| Type | Description |
|---|---|
<Document> |
Collection document with replaced fields. A document’s data type is taken from its collection’s name. For example,
|
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"
}