Marcin
CCConvex Community
•Created by Marcin on 12/5/2024 in #support-community
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;
},
});
6 replies