Search code examples
arraystypescriptmongodbprisma

MongoDB prisma add new data to array


I want to push new data to array, but it got an error, but when there is no data in array, it create successfully, and throw error like this:

- error Error:
Invalid `prisma.user.update()` invocation:

Unique constraint failed on the constraint: `_id_`

Here is my code:

post.ts

    const { id } = req.query as { id: string }
    const { title, animeId, image } = req.body as { title: string; animeId: string; image: string }
    if (!title || !animeId || !image) return res.status(400).send("Missing fields");

    return prisma.user.update({
        where: {
            id: id as string
        },
        data: {
            saved: {
                create: {
                    title,
                    animeId,
                    image
                }
            }
        },
        include: {
            saved: true
        }
    }).then(data => {
        return res.status(200).send(data.saved)
    })

schema.prisma

model User {
  id       String       @id @default(auto()) @map("_id") @db.ObjectId
  created  DateTime     @default(now())
  name     String
  email    String       @unique
  password String
  saved    SavedAnime[]
}

model SavedAnime {
  id      String @id @default(auto()) @map("_id") @db.ObjectId
  user    User?  @relation(fields: [id], references: [id])
  title   String
  animeId String
  image   String
}

I have tried debugging, it run normally, but yeah, when I want to add another new data in array, I got that error.


Solution

  • never mind, I got the fix

    the issue was from schema.prisma

    model User {
      id       String       @id @default(auto()) @map("_id") @db.ObjectId
      created  DateTime     @default(now())
      name     String
      email    String       @unique
      password String
      saved    SavedAnime[]
    }
    
    model SavedAnime {
      id      String  @id @default(auto()) @map("_id") @db.ObjectId
      user    User?   @relation(fields: [userId], references: [id])
      userId  String? @db.ObjectId
      title   String
      animeId String
      image   String
    }
    

    the relation needs userId to make sure the userId is same as the user who saved it