P
Prisma7mo ago
Werdox

omit with condition

I want to only omit certain fields if a condition in the same thing I'm querying is true example:
const channels = await prisma.channel.findMany({
where: { ownerId: userId },
omit: { name: /* Only omit 'name' if the channel type is 1 */ },
});
const channels = await prisma.channel.findMany({
where: { ownerId: userId },
omit: { name: /* Only omit 'name' if the channel type is 1 */ },
});
Solution:
--- Here is the omitArray function for anyone finding this later ```ts export function omitArray<Data extends object, Keys extends keyof Data>( data: Data[],...
Jump to solution
7 Replies
jonfanz
jonfanz7mo ago
Not currently possible. As a work around, you could put the condition inside your where clause. Query once where channel type is 1 (and omit name). Query another time where channel type is not 1 and don’t omit
Werdox
WerdoxOP7mo ago
Hmm this would be possible but it intentionally orders the list to type 1 and then type 0
jonfanz
jonfanz7mo ago
Hm yes, that’s true. How large are these data sets? Would you be paginating?
Werdox
WerdoxOP7mo ago
Pretty small for now, so no paginating
jonfanz
jonfanz7mo ago
You could then pull everything in and shuffle it. It’s not an ideal solution but it would at least be a proof of concept Otherwise, you could just pull data from your db and then iterate through setting name to undefined where needed Both are not great options, unfortunately
Werdox
WerdoxOP7mo ago
Hmm I need the data in the original order. I do have an omitArray function which removes a property from all indecies of an array I guess I should use that then. Thought there might be a native solution.
Solution
Werdox
Werdox7mo ago
--- Here is the omitArray function for anyone finding this later
export function omitArray<Data extends object, Keys extends keyof Data>(
data: Data[],
keys: Keys[]
): Omit<Data, (typeof keys)[number]>[] {
const result = [];

for (const obj of [...data]) {
const modifiedObj = { ...obj };
for (const key of keys) {
delete modifiedObj[key];
}

result.push(modifiedObj);
}

return result;
}
export function omitArray<Data extends object, Keys extends keyof Data>(
data: Data[],
keys: Keys[]
): Omit<Data, (typeof keys)[number]>[] {
const result = [];

for (const obj of [...data]) {
const modifiedObj = { ...obj };
for (const key of keys) {
delete modifiedObj[key];
}

result.push(modifiedObj);
}

return result;
}
Want results from more Discord servers?
Add your server