backpack1098B
Convex Communityβ€’2y agoβ€’
8 replies
backpack1098

query and update inside for-loop

(not urgent)
hi team! im running into a weird situation. hopefully it's just that im blind to the logic implementation. i have the following code that "updates" the usage table with the image size the user uploaded
await Promise.all(
  args.storageIds.map(async (s) => {
    const metadata = await ctx.db.system.get(s.storageId as Id<"_storage">)
    console.log(
      "πŸš€ ~ file: images.ts:43 ~ args.storageIds.map ~ metadata:",
      metadata.size
    ) // 93558, 68153, 68948

    const usage = await ctx.db
      .query("usage")
      .withIndex("by_userId", (q) => q.eq("userId", ctx.userId))
      .unique()
    console.log(
      "πŸš€ ~ file: images.ts:53 ~ args.storageIds.map ~ usage:",
      usage.used
    ) // 0, 0, 0, should be 0, 93558, 93558 + 68153
    await ctx.db.patch(usage._id, { used: usage.used + metadata.size })

    await ctx.db.insert("images", {
      userId: ctx.userId,
      uploadedImageId: s.storageId,
    })
  })
)

im not sure why the usage returned is 0, 0, 0 where i'd expect it to be 0, 93558, 93558 + 68153. i managed to change the implementation to the following:
let size = 0
await Promise.all(
  args.storageIds.map(async (s) => {
    const metadata = await ctx.db.system.get(s.storageId as Id<"_storage">)
    size += metadata.size
    await ctx.db.insert("images", {
      userId: ctx.userId,
      uploadedImageId: s.storageId,
    })
  })
)

const usage = await ctx.db
  .query("usage")
  .withIndex("by_userId", (q) => q.eq("userId", ctx.userId))
  .unique()
await ctx.db.patch(usage._id, { used: usage.used + size })

which is def more efficient and worked. im just curious if there's some special case with my first implementation. thank you.
Was this page helpful?