Fauna does not provide cascading deletes out-of-the-box for user-defined documents. That is, if you have a document "A" that includes a reference to another document "B", deleting "A" does not affect "B", and deleting "B" does not affect "A".
Cascading deletes can be achieved with FQL. As an example to demonstrate the solution, consider two collections Employee
and Payroll
, where the Payroll
collection has a reference to documents in the Employee
collection.
An example Employee
document looks like this:
{
id: "367642487982915661",
coll: Employee,
ts: Time("2023-06-15T23:00:48.445Z"),
name: "Claire",
title: "Associate",
department: "Finance"
}
The corresponding document in the Payroll collection looks like this:
{
id: "367642536680882249",
coll: Payroll,
ts: Time("2023-06-15T23:01:34.880Z"),
employee: Employee.byId("367642487982915661"),
salary: 5000
}
If you delete the Employee
document for Claire, it does not automatically delete the associated Payroll
document.
To do this, you will need to create an index on the Payroll
collection to get the Payroll
document based on the Employee id.
Payroll.definition.update({
indexes: {
byEmployee: {
terms: [
{
field: "employee"
}
],
}
}
}
)
The following query deletes the employee Claire from the Employee
collection and uses the newly created index to delete the related entry from the Payroll
collection at the same time.
let emp_id = "367642487982915661"
let emp = Employee.byId(emp_id)
let payroll = Payroll.byEmployee(emp)
{
emp.delete()
payroll.forEach(.delete())
}
This can be further extended to delete Employee
references in multiple collections at the same time by creating necessary indexes in each of those collections and using the same query as above for all such collections.
For example, the following query fetches the Employee
document from two collections Payroll
and AccessDirectory
using indexes and deletes Employee
entries in both of them at the same time.
let emp_id = "367642487982915661"
let emp = Employee.byId(emp_id)
let payroll = Payroll.byEmployee(emp)
let accessDir = AccessDirectory.byEmployee(emp)
{
emp.delete()
payroll.forEach(.delete())
accessDir.forEach(.delete())
}