Michael Holmes
Michael Holmes15mo ago

Excluding fields in a query?

Is doing something like this the best way to remove fields or is there a way to do this directly in the query? import { Doc } from '../../_generated/dataModel'; const removePrivateOrganizationData = (organizations: Doc<'organizations'>[]) => { return organizations.forEach(org => { delete org.monthlyStripeSubscriptionId; delete org.yearlyStripeSubscriptionId; delete org.isApproved; delete org.evaluationCentsLimit; delete org.generationCentsLimit; delete org.paymentCentsBalance; delete org.payoutCentsBalance; delete org.isBanned; delete org.lastEditorId; }); }; export default removePrivateOrganizationData;
4 Replies
Michal Srb
Michal Srb15mo ago
Hey @Michael Holmes , you could select fields instead of excluding:
function removePrivateOrganizationData(organizations: Doc<'organizations'>[]) => {
return organizations.map(({fieldWeWant, anotherFieldWeWant}) => ({fieldWeWant, anotherFieldWeWant}));
};
function removePrivateOrganizationData(organizations: Doc<'organizations'>[]) => {
return organizations.map(({fieldWeWant, anotherFieldWeWant}) => ({fieldWeWant, anotherFieldWeWant}));
};
If you do want to exclude, I'd use a similar functional pure style to avoid mutating state, but the result will match:
function removePrivateOrganizationData(organizations: Doc<'organizations'>[]) => {
return organizations.map(({monthlyStripeSubscriptionId, yearlyStripeSubscriptionId, isApproved, ...fields}) => fields);
};
function removePrivateOrganizationData(organizations: Doc<'organizations'>[]) => {
return organizations.map(({monthlyStripeSubscriptionId, yearlyStripeSubscriptionId, isApproved, ...fields}) => fields);
};
The destructuring will bind all the fields you don't want to return, and the function will return the rest. Taking a step back, you might also want to structure your public vs private data into multiple documents linked via foreign keys. In the future we might provide a layer that would enable you to express visibility/privacy rules for individual fields.
Michael Holmes
Michael HolmesOP15mo ago
Ok I'll go with multiple documents. Is there a preferred way to create one-to-one relationships in convex? Something like this? organizations: defineTable({ accountId: v.optional(v.union(v.id('organizationAccounts'), v.null())), })
Michal Srb
Michal Srb15mo ago
Schemas | Convex Developer Hub
Schema validation keeps your Convex data neat and tidy. It also gives you end-to-end TypeScript type safety!
Michael Holmes
Michael HolmesOP15mo ago
Nice!

Did you find this page helpful?