shadow_aya
shadow_aya•15mo ago

Bulk deletes and indexes

export const removeExpired = internalMutation({
async handler(ctx) {

const expiredSessions = await ctx.db
.query("siteSessions")
.withIndex("by_expires")
.filter((q) =>
q.lt(q.field("expires"), Date.now())
)
.collect()

for (const session of expiredSessions) {
await ctx.db.delete(session._id);
}
},
});
export const removeExpired = internalMutation({
async handler(ctx) {

const expiredSessions = await ctx.db
.query("siteSessions")
.withIndex("by_expires")
.filter((q) =>
q.lt(q.field("expires"), Date.now())
)
.collect()

for (const session of expiredSessions) {
await ctx.db.delete(session._id);
}
},
});
this definitely feels a bit wrong. do I mass delete like this?
3 Replies
Indy
Indy•15mo ago
Hi there are a couple things that stick out with this: 1. Your query isn't actually using the index to filter the query. To actually use the expires index you need to use the second parameter to withIndex. https://docs.convex.dev/database/indexes/#querying-documents-using-indexes 2. Second, though the delete loop will work. A slightly better pattern is to use the map with Promise.all pattern as shown for a sub query here: https://docs.convex.dev/tutorial/client#use-the-new-index-to-query-likes-data
2: Convex and your app | Convex Developer Hub
Learn how to connect your project to Convex and quickly build out new fullstack features
Indexes | Convex Developer Hub
Indexes are a data structure that allow you to speed up your
shadow_aya
shadow_ayaOP•15mo ago
oh sh- I completely missed the first point. sometimes I am terrible at reading docs, sorry :KaimonNotLikeThis:
Indy
Indy•15mo ago
No need to apologize! I am glad you asked and hopefully learned something. 🙂

Did you find this page helpful?