Prisma: Incorrectly identifying existing items where the list contains any of the specified items

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;
}

Answer №1

The issue I encountered was not related to the above discussion, but rather with historical data containing multiple records. The code I shared was expecting a single record instead.

To address this, I updated the code to combine historical data when an array of phones is provided and there are multiple records present for those phones.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing React forwardRef with a functional component

Looking at my code, I have defined an interface as follows: export interface INTERFACE1{ name?: string; label?: string; } Additionally, there is a function component implemented like this: export function FUNCTION1({ name, label }: INTERFACE1) { ...

The reason behind the clickable issue with my duplicate <ion-select>

I've been working on a form using HTML, CSS, and JavaScript where I implemented an "Add" button to duplicate the form. The issue arises with the ion-select element within the duplicated form. While the original form displays all predefined options upo ...

Using Vercel with Next JS to implement a Stripe webhook listener

Currently developing an online shop using Next JS with a stripe payment system. I need to track the completion or cancellation of payments in order to update the status of my orders as paid or unpaid. When working on localhost, the following code in packa ...

Mismatch between TypeScript library and Angular web application: certain properties are absent

I am currently facing a dilemma with my two angular projects. The first one is a library while the second one is a regular Angular webapp. Within my library project, I have the following code snippet: class User { firstName: string; lastName: stri ...

Encountering an issue when attempting to deploy Next.js(V13) to Vercel that involves the @tiptap

I am facing an issue while deploying my NextJs (V13) to Vercel. The error I am encountering can be seen in this image: () It appears that the problem is related to the useEditor function from the @tiptap/react library. Below is a snippet of my create page ...

How to use Sequelize for aggregating data within nested includes on PostgreSQL

The database I'm working with consists of several tables that are relevant to my project, including users, listings, and reviews. Each user can have multiple listings, while each listing can have multiple reviews. A specific column in the reviews ta ...

Google Cloud Run enables Firebase Hosting to "rewrite" and access Next.js applications

We are currently utilizing Firebase Hosting for our project. A Next.js application named "knowledge" is deployed on Google Cloud Run within the same GCP project. Following the guidelines provided in the Firebase documentation, our firebase.json configurati ...

Issue with React TSX component in NextJs 14.0.4: Local MP3 files cannot be played, only external online MP3 files work

I have created a component that wraps around HTML audio and source tags. It functions perfectly when playing mp3 files from an external source, like this sound clip . However, it returns a GET 404 error when trying to access local mp3 files. Can anyone exp ...

What could be causing the errors I'm encountering in my TypeScript component within AngularJS?

I am working with an AngularJS component written in TypeScript called news.component.ts. This component makes a call to a service named google.service.ts in order to fetch news RSS using a service that converts XML to JSON. Within the NewsComponent, I hav ...

Generating a JavaScript bundle using the npm TypeScript compiler

Is there a way to compile TypeScript source files into one JavaScript bundle file? We have developed a tool on node.js and are currently using the following TypeScript compilation code: var ts = require('typescript'); ... var program = ts.creat ...

Ways to toggle visibility of menu options in a Next.js application based on user authentication status

I need to conditionally show the logout button only if a user is logged in. Here is my _app.js file: import React from "react"; import App from "next/app"; import Navbar from "../components/navbar"; import Layout from "../components/layouts/mainLayout"; ...

Centering on request, Google Maps adjusts its view to focus on

When I select a row, I want to set the map center to the provided coordinates in Primeng. The issue is that while this.options works fine in ngOnInit, it doesn't work when called in the showCords() function. Below is my code: gmap.component.ts im ...

Error message in Typescript: The argument type '() => () => Socket<DefaultEventsMap, DefaultEventsMap>' cannot be assigned to a parameter of type 'EffectCallback'

I am struggling to comprehend how I should specifically type constrain in order to prevent the error within my useEffect. One approach is to either cast my newSocket or specify the return value of my useEffect as any, but I am hesitant about that solution. ...

"An error occurs when attempting to access "this" in a static method as it

Just diving into the world of React and Typescript and currently exploring React hooks. Encountered a problem that's leaving me scratching my head. Here's the hook I'm using to fetch data: export const useFetch = <T>( fetchFunc: ( ...

Utilizing getUserMedia to capture portrait shots with the back camera

I am encountering an issue with starting the back camera in portrait mode using navigator.mediaDevices.getUserMedia in React. The camera does not appear to be taking into account the constraints I have set. Below is how the code looks for initialization: ...

Creating HTTP-only cookies within a NextJS middleware

Having an issue with updating access token in my middleware when the current one expires; here's my approach: Generate a new token Send it to an API route which adds the token to its response header. The problem arises when the middleware receives t ...

What is the method to group a TypeScript array based on a key from an object within the array?

I am dealing with an array called products that requires grouping based on the Product._shop_id. export class Product { _id: string; _shop_id: string; } export class Variant { variant_id: string; } export interface ShoppingCart { Variant: ...

After the "markerClick" event triggers in Angular2 SebmGoogleMapMarker, the view fails to update

I am dealing with an array structured like this: locations: marker[] = [ {id: '1', lat: 51.5239935252832, lng: 5.137663903579778, content: 'Kids Jungalow (5p)', iconUrl: 'img/marker.png'}, {id: '2&apos ...

Steps to retrieve the search box input value and submit it in an AngularJs component using the Enter key

I'm facing an issue where I am trying to fetch the search list using speciesName from a table. However, when I attempt to retrieve the data by pressing the enter key, it is returning an error stating that the input data is undefined. Is there a way ...

Encountering a type-safety problem while attempting to add data to a table with Drizzle

My database schema is structured like so: export const Organization = pgTable( "Organization", { id: text("id").primaryKey().notNull(), name: text("name").notNull(), createdAt: timestamp("c ...