#Log Message[orgs.getForCurrentUser] Unexpected error, returning null r.db.insert is not a function

4 messages · Page 1 of 1 (latest)

final patio
#

I keep getting this error even after creating a fresh project in next. Log Message

[orgs.getForCurrentUser] Unexpected error, returning null r.db.insert is not a function

grave rivetBOT
#

Hi @final patio. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

The error message r.db.insert is not a function suggests that you are trying to call db.insert in a context where it is not available—most likely inside a Convex query or action rather than a mutation.

In Convex, only mutations have access to ctx.db.insert for writing data. Queries are read-only and do not have access to database write methods like insert, patch, or delete. Similarly, actions do not have direct access to ctx.db, but can call mutations using ctx.runMutation if you need to perform a write operation from an action.

Here's how you should structure your code:

  • If you need to insert data, use a mutation:
    import { mutation } from "./_generated/server";
    import { v } from "convex/values";
    
    export const createOrg = mutation({
      args: { name: v.string() },
      handler: async (ctx, args) => {
        const orgId = await ctx.db.insert("orgs", { name: args.name });
        return orgId;
      },
    });
    
  • If you are in an action and need to write data, use ctx.runMutation:
    import { action } from "./_generated/server";
    import { api } from "./_generated/api";
    import { v } from "convex/values";
    
    export const createOrgAction = action({
      args: { name: v.string() },
      handler: async (ctx, args) => {
        const orgId = await ctx.runMutation(api.orgs.createOrg, { name: args.name });
        return orgId;
      },
    });
    
  • Queries should only read data and never call db.insert.

If you are seeing this error in a function like orgs.getForCurrentUser, double-check that you are not calling db.insert or any other write method inside a query. If you need to create a user or org if it doesn't exist, you should do that in a mutation, not a query.

#

For more details, see the Convex documentation on writing data and the API reference for db.insert.

If you continue to see this error even after moving your code to a mutation, ensure that your imports are correct and that you are not accidentally calling a mutation from a query or vice versa. If you are using actions, remember to use ctx.runMutation to perform writes, and import the generated API as shown above.

If you need to debug further, consider enabling verbose logging as described in the debugging guide.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: