Update documents
This tutorial shows how to update select document fields and how to replace the whole document. The tutorial’s examples use Fauna’s demo data.
Fetch a document
Each document has an immutable id
that’s unique within its collection. You can
specify an id
when you create a document. If you don’t specify an id
,
Fauna auto-generates one.
The following query creates a document with a specific id
in the Product
collection:
// Create a document with a specific `id`
Product.create({
id: "392886847463751746",
name: "limes",
description: "Organic, 1 ct",
price: 0.65
})
Use byId()
to
get the document you created using its id
:
Product.byId("392886847463751746")
For simplicity, other examples in this tutorial also use
byId()
to
fetch the document you created.
Update a field in a document
Use update()
to
update an existing field value in a document:
// Update the "description" value
Product.byId("392886847463751746")
?.update({
description: "Organic, 2 ct"
})
Add a field to a document
You can also use update()
to add a new field to a document:
// Add the "quantity" field
Product.byId("392886847463751746")
?.update({
quantity: 300
})
Remove a field from a document
To remove a field, set the field value to null
:
// Remove the "price" field
Product.byId("392886847463751746")
?.update({
price: null
})
Update fields in select documents
Use forEach()
to iterate
through a set of documents and perform writes:
// Get products named "limes"
let products = Product.byName("limes")
// Update each product's `name` to "key limes"
products.forEach((product) => product.updateData({
name: "key limes"
}))
// Get all products named "key limes"
Product.byName("key limes") { name, description }
Replace whole document contents
Use replace()
to replace
an entire document. Any fields not included in the replacement data are removed.
// Replaces a document
Product.byId("392886847463751746")
?.replace({
name: "limes",
description: "Organic, 1 ct",
price: 0.65
})
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!