RJ
RJ2y ago

How to delete a field on a table?

I'm having some trouble figuring out how to remove a field from a table since the new schema validation features landed. When I try to do so, I get a schema validation error. I figured perhaps I needed first to "unset" all of the values for that field, so I tried to first set it as v.optional() and then to db.patch(tableId, { fieldToDelete: undefined }) each document in the table, but this had no effect (is that the expected behavior?). What might I be doing wrong?
3 Replies
RJ
RJOP2y ago
I can DM the terminal output of the validation failure, if that's helpful.
lee
lee2y ago
Hi RJ! We've noticed this confusion before and we've been considering what to do about it. For now, db.patch (along with db.insert and db.replace and JSON.stringify) ignores all fields with value undefined, so it's expected that db.patch(tableId, { fieldToDelete: undefined }) would have no effect. The workaround for now is to do
const doc = await db.get(docId);
delete doc.fieldToDelete;
await db.replace(docId, doc);
const doc = await db.get(docId);
delete doc.fieldToDelete;
await db.replace(docId, doc);
This code is equivalent to what you expected: - patch also does a get under the hood to merge the objects, so get-replace is just as fast as patch - every mutation is a transaction, so it's still atomic this workaround doesn't look so clean though. it's good feedback that you expected db.patch(id, {field: undefined}) to work, thanks!
RJ
RJOP2y ago
Ah ok got it, thank you for the explanation and solution!

Did you find this page helpful?