David Alonso
David Alonso•5mo ago

How to easily update a single nested field?

Why does the dynamic of updating a top level field not apply to nested fields? For instance, why can't I do:
await ctx.db.patch(doc._id, {
// @ts-ignore
"properties.queryType": "firestoreDocumentFieldFromPath",
});
await ctx.db.patch(doc._id, {
// @ts-ignore
"properties.queryType": "firestoreDocumentFieldFromPath",
});
or this without having to spread the existing object
await ctx.db.patch(doc._id, {
// @ts-ignore
properties: {
// ...doc.properties,
queryType: "firestoreDocumentFieldFromPath",
},
});
await ctx.db.patch(doc._id, {
// @ts-ignore
properties: {
// ...doc.properties,
queryType: "firestoreDocumentFieldFromPath",
},
});
3 Replies
Hmza
Hmza•5mo ago
its more efficient this way 👇 const doc = await ctx.db.get(mdoc._id); const updatedProperties = { ...doc.properties, // spread the existing properties queryType: "firestoreDocumentFieldFromPath", }; await ctx.db.patch(doc._id, { properties: updatedProperties, // update the properties object }); i think the reason is to make transactional updates and avoid any partial update errors also the structure is more flat this way, easy to understand. also doing the nesting in memory and then telling convex exactly what todo would make it faster.
erquhart
erquhart•5mo ago
I can't speak to the "why" here but it does say in docs that nested field updates overwrite the whole field (so I was wrong about this when we spoke). That said, getting by id and spreading is reliable and fast. If this is about ergonomics, you could write a very short helper that handles the getting and spreading for you.
David Alonso
David AlonsoOP•5mo ago
I think that would be a useful helper for convex-helpers

Did you find this page helpful?