Marcin
Marcin•2mo ago

Getting current user id in mutation

Hi! I'm trying to post a comment related to defined item. I pass itemId as an argument but i want to use current user's id as a comment author. I've configured simple password login. I could see in database that fields i used in withIndex are equal but i couldnt pass identity.subject as is as it is not Id<users> field. thus query returns empty array. How to do this correctly? Should I use users collection instead of authAccounts? export const add = mutation({ args: { text: v.string(), itemId: v.id('items'), }, handler: async (ctx, args) => { const identity = await ctx.auth.getUserIdentity(); if (!identity) { throw new Error('Not authenticated'); } const user = await ctx.db .query('authAccounts') .withIndex('userIdAndProvider', (q) => q.eq('userId', identity.subject as Id<'users'>)) .first(); if (!user) { throw new Error('User not found'); } const comment = await ctx.db.insert('comments', { text: args.text, itemId: args.itemId, userId: user.userId, createdAt: Date.now(), }); return comment; }, });
3 Replies
Convex Bot
Convex Bot•2mo ago
Thanks for posting in <#1088161997662724167>. Reminder: If you have a Convex Pro account, use the Convex Dashboard to file support tickets. - Provide context: What are you trying to achieve, what is the end-user interaction, what are you seeing? (full error message, command output, etc.) - Use search.convex.dev to search Docs, Stack, and Discord all at once. - Additionally, you can post your questions in the Convex Community's <#1228095053885476985> channel to receive a response from AI. - Avoid tagging staff unless specifically instructed. Thank you!
ballingt
ballingt•2mo ago
How to do this correctly? Should I use users collection instead of authAccounts?
Yes, since you're trying to link a user to this comment, not an auth account @Marcin check out getUserAuthId as used in https://github.com/get-convex/convex-auth/blob/main/test/convex/users.ts
I could see in database that fields i used in withIndex are equal but i couldnt pass identity.subject as is as it is not Id<users> field. thus query returns empty array.
To see how to do this, check out the source for that function https://github.com/get-convex/convex-auth/blob/10b4924e0b8e0a97d2130c01eaf02c8dd2b25fb6/src/server/implementation/index.ts#L463-L470
Marcin
MarcinOP•2mo ago
Oh i see. Thats so simple now! 🙂 Thank you

Did you find this page helpful?