Within my Prisma model, I have a property designated to store a list of phone numbers in the format
phones String[] @unique
When making an API call with a model that may include one or more phone numbers, my goal is to locate any existing record where any phone matches any of the given phone numbers.
I attempted to achieve this using the code snippet below:
However, I started encountering unique constraint errors when attempting to create a new record (indicating that a record with the same phone number already exists), revealing that there might be an issue with my query logic.
const body = await request.json();
const records = await prisma.person.findMany({
where: {
phones: {
hasSome: body.phones,
},
},
});
if (records.length > 0) {
const updated = await UpdatePerson(records[0], body);
return NextResponse.json(false, {
status: 200,
});
} else {
const created = await CreatePerson(body);
return NextResponse.json(false, {
status: 200,
});
}
}
For the sake of completeness and transparency (as a novice in working with Prisma), the following are the creation and editing methods:
async function CreatePerson(data: Person) {
try {
const result = await prisma.person.create({
data,
});
return result;
} catch (error) {
throw new Error("Failed to create person");
}
}
async function UpdatePerson(
existing: Person,
data: Person,
) {
try {
const updatedPerson = await prisma.person.update({
where: {
id: existing.id,
},
data: {
....
phones: addMissingItems(existing.phones, data.phones),
email: existing.email ? existing.email : data.email ? data.email : null,
In addition, there is a helper method designed to merge two string arrays:
export function addMissingItems(
firstArray: string[],
secondArray: string[],
): string[] {
// Make a copy of the second array to prevent altering the original
const resultArray = secondArray.slice();
// Iterate over items in the first array
for (const item of firstArray) {
// Check if the item does not exist in the second array
if (!resultArray.includes(item)) {
// Add the item to the result array
resultArray.push(item);
}
}
return resultArray;
}