CodeWithAntonio
CodeWithAntonio•2y ago

Query both unset and false

Hi Everyone! I love using Convex so far, it is really easy and a lot of great features out of the box. Right now I am trying to figure out a best practice to implement a "soft delete". I have defined a schema documents:
export default defineSchema({
documents: defineTable({
title: v.string(),
userId: v.string(),
isArchived: v.optional(v.boolean()),
})
.index("by_user_id", ["userId"])
.index("by_title", ["title"])
});
export default defineSchema({
documents: defineTable({
title: v.string(),
userId: v.string(),
isArchived: v.optional(v.boolean()),
})
.index("by_user_id", ["userId"])
.index("by_title", ["title"])
});
The problem arrives when I try to only the non-archived documents, this is the filter I am using: .filter((q) => q.eq("isArchived", undefined)) If I attempt to filter by false instead of undefined I get a typescript error. And in my restore function, I patch the document by setting isArchived to false.
const document = await ctx.db.patch(args.id, {
isArchived: false,
});
const document = await ctx.db.patch(args.id, {
isArchived: false,
});
I assume it can work by me setting the isArchived: undefined instead of false But I feel like I am doing something wrong here? Can I query an optional, boolean field by both undefined | false ? P.S. My userId is a string because I dont have the need for users table atm, I just use Clerk's userId.
6 Replies
Michal Srb
Michal Srb•2y ago
Hey @CodeWithAntonio , you can use an q.or to combine the two conditions (equals undefined or equals false): https://docs.convex.dev/database/reading-data#combining-operators
ian
ian•2y ago
Something like: q.or(q.eq(q.field("isArchived"), false), q.eq(q.field("isArchived"), undefined)) Note: for filter, you have to specify q.field as the first parameter. Otherwise you'll just be finding documents where the string "isArchived" is false (which will always be the case). This is a rough edge we know about and are thinking about improving
CodeWithAntonio
CodeWithAntonioOP•2y ago
Works like a charm! I got some "cannot use undefined as filter" message, but it went away after I re-run npx convex dev, must've been unsynsced schema or some of my unsaved changes. Thanks for the insight about additional query operator and the q.field !
CodeWithAntonio
CodeWithAntonioOP•2y ago
Something that could be useful, since I come from Prisma background is having the ability for "default" for optional fields 🙂
No description
Mosen
Mosen•2y ago
+1 for defaults
Michal Srb
Michal Srb•2y ago
Thanks for the feedback about defaults, we are thinking through the solutions for this problem. Keep the feedback coming! 🙂

Did you find this page helpful?