#How to mutate array
4 messages · Page 1 of 1 (latest)
Hi @carmine kelp. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
In Convex, you can model relationships between documents either by embedding related data directly in arrays (embedding) or by using references (relations) such as storing IDs of related documents. Here’s how you can mutate (add, remove, or update) these relationships:
Mutating Array Embeddings
If you store related data directly as an array of objects or IDs within a document (embedding), you mutate the array by updating the document with the new array value. For example, to add a phone number to a person’s array of phone numbers:
await ctx.db.patch(person._id, {
phone_numbers: [...person.phone_numbers, { type: "mobile", number: "1234567890" }]
});
This approach is simple and efficient for small, bounded lists. However, you should be aware of Convex’s array limitations: arrays are limited to 8192 entries, and it’s recommended to keep arrays small (on the order of 10 items) for performance reasons. Also, you cannot index into arrays, so querying by an embedded value is not efficient. This method is best when you don’t need to look up documents by the embedded value and the list is naturally smallSuggestions on schema best practice?, Relationship Structures: Many-to-many.
Mutating Array Relations (References)
If you use references (relations), you typically store an array of IDs in one document, or use a separate table to represent the relationship. To mutate these, you update the array of IDs or insert/delete relationship documents. For example, to add a submission ID to a participant:
await ctx.db.patch(participant._id, {
submissionIds: [...participant.submissionIds, newSubmissionId]
});
Or, for a many-to-many relationship using a join table:
await ctx.db.insert("roles_to_permissions", {
rolesId: roleId,
permissionsId: permissionId
});
This approach is more scalable and allows for efficient querying in both directions if you use indexes. It’s preferred when the number of related items can grow large or you need to query by the related valueRelationship Structures: One-to-many, Many-to-many relationships.
Summary
- Embedding (array of objects/IDs): Simple, fast for small lists, but not scalable or easily queryable by embedded values.
- Relations (references/IDs or join tables): More flexible and scalable, supports efficient queries, but requires more schema setup.