Jeff CJ
Convex Community10mo ago
15 replies
Jeff C

Another call to this mutation changed the document

I encountered this error and find it very confusing. I have some parallel actions going that should be updating totally separate batches of data, but still getting this error randomly.

I made a minimal reproduction that should have no change of mutual edits, but still consistently fails with the error above... Can someone please tell me if I'm missing some fundamental concept of the db operations here?


import { v } from 'convex/values'
import { internal } from './_generated/api'
import { action, internalMutation } from './_generated/server'

/**
 * Updates the table values for a given groupId
 */
export const processGroup = internalMutation({
  args: { groupId: v.string() },
  handler: async (ctx, { groupId }) => {
    // Get all existing docs with this groupId
    const existingDocs = await ctx.db
      .query('testDocs')
      .filter((q) => q.eq(q.field('groupId'), groupId))
      .collect()

    for (const existingDoc of existingDocs) {
      await ctx.db.delete(existingDoc._id)
    }

    for (let i = 0; i < 10; i++) {
      await ctx.db.insert('testDocs', { groupId, value: i.toString() })
    }
  }
})

export const trigger = action({
  handler: async (ctx) => {
    const groupIds: string[] = []
    for (let i = 0; i < 10; i++) {
      groupIds.push(i.toString())
    }
    await Promise.all(
      groupIds.map(async (groupId) => {
        await ctx.runMutation(internal.dbTest.processGroup, { groupId })
      })
    )
  }
})
Was this page helpful?