Prisma MongoDB adds new data to an existing array

When attempting to add new data to an array, I encountered an error. Strangely enough, the creation is successful when the array is empty, but once it contains data, I get the following error message:

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

Unique constraint failed on the constraint: `_id_`

Below is the code snippet:

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
}

Despite debugging the code and finding no issues, the error still arises when trying to insert new data into the array.

Answer №1

Disregard that, I found the solution

The problem originated from schema.prisma file

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
}

It is essential for the relation to include userId in order to ensure it matches the user who stored it

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

A helpful guide on selecting a random array within a multidimensional array using php

Looking to generate a random array: For instance: $randomNavItems= array( array( slug => "top10.php", title => "Top 10 best" ), array( slug => "index.php", title => "Main" ), arr ...

Troubles encountered when trying to execute mocha within Firebase functions

My latest project involved developing a Node/Typescript app that interacted with data from Firebase Cloud Firestore. The app performed flawlessly, and I conducted endpoint testing using simple mocha commands on the generated .js file. Below is an example o ...

Is there a way to exclude a column from the query result in MongoDB for Java?

I am struggling with a MongoDB query and need some help. Here is the query: db.getCollection("author").find({}, {_id: 0}) How can I achieve this in Java? Currently, I am only able to query all columns, but I want to learn how to exclude a specif ...

Deleting items from a JavaScript object array in Angular using TypeScript can be achieved by using various methods and

Here is the structure of my object array: 0: {Name: "Albert", Id: 32} 1: {Name: "George", Id: 34} 2: {Name: "Jane", Id: 35} Although the request is successful, the array remains unchanged. However, upon refreshing the app, the item (student) is deleted. ...

Retrieve the top N elements of an Array with their corresponding indices

I have an array with Integers as shown below: val my_array = Array(10, 20, 6, 31, 0, 2, -2) I am trying to extract the top 3 elements from this array along with their respective indices (either through a single function or two separate functions). For i ...

What is the best way to execute a task in Grunt when supplied with a dynamically-generated array of filenames?

Although I am relatively new to using Grunt, I have developed a good understanding of how tasks are installed and executed. Currently, I am successfully running tasks such as minifying js, copying files, and executing jshint. Now, my goal is to implement ...

Resolving Node.js Absolute Module Paths with TypeScript

Currently, I am facing an issue where the modules need to be resolved based on the baseUrl so that the output code is compatible with node.js. Here is my file path: src/server/index.ts import express = require('express'); import {port, database ...

Arrange information into sections

This Angular code is used to format text into profile page as blocks of data: <div class="element-box"> <div class="details-wrapper"> <p><b class="label">Remote IP</b>{{apiattempt.remote_ip}}</p> <p>< ...

Retrieve specific field for all users using mongo .find

Querying db.users.find({}) will fetch all user data with all fields included. Is there a way to compose a query that only retrieves the 'email' field for every user? ...

Tips on narrowing down the type of callback event depending on the specific event name

I've been working on implementing an event emitter, and the code is pretty straightforward. Currently, tsc is flagging the event type in eventHandler as 'ErrorEvent' | 'MessageEvent'. This seems to be causing some confusion, and I ...

Is there a method to ensure that an array size matches its expected value during compilation?

The memory pool table, mem_pool_tbl, is implemented as an array with the TBL_ID_TYPE enum defining its index: typedef enum { TBL_ID_BEGIN = 0; TBL_ID_1, TBL_ID_2, TBL_ID_MAX, }TBL_ID_TYPE; int mem_pool_tbl[TBL_ID_TYPE] = {1, 2, 3, 4} I a ...

Send the information to MongoDB in the form of an object, utilize it as a query, and then perform

I have a document stored in my mongoDB database. https://i.sstatic.net/2DI2p.png When a user types something into an input field on the frontend, for example 'test', the object passed looks like this: {'countdown': 'test'} ...

Locate and adjust, retrieve the information, analyze it, and store it - Mongoid

In my Rails application, I am utilizing Mongoid and came across the find_and_modify command for updating a document immediately after finding it. Let's take the example of a collection called User with the following document structure: name points ...

Transferring a collection in Spring using MongoDB

I am currently working with Spring Data and MongoDB. I am interested in transferring documents from one collection to another programmatically, rather than using the command line. Is there a method to accomplish this task without having to iterate throug ...

Synchronization of nested queries in MongoDB

I have the following two collections: 1) Users: {name: xyz, email:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8aebe8e9caf2fff0a4e9e5e7">[email protected]</a>} 2) Posts: {_id: 12345678, time:as ...

Return attention to the original content of the page once the success banner at the top has been closed

I am working on a React application with multiple pages that all use a shared banner component. After performing an action on the screen, a success or error message appears at the top in the banner. The issue I'm facing is that when the user dismiss ...

How to Add Data from Another MongoDB Collection in Mongo/Meteor

I am looking to incorporate a document from one collection into another, specifically a UoM into Products. Template.NewProduct.helpers({ ... uoms: function() { return UoM.find(); }, ... }); Template.NewProduct.events({ //Submit and Add to ...

Guide to accessing component methods within slots using the Vue 3 Composition API

I have child components within a slot in a parent component and I am trying to call methods on them. Here are the steps I followed: Use useSlots to retrieve the child components as objects Expose the method in the child component using defineExpose Call t ...

forEach was unable to determine the appropriate data types

define function a(param: number): number; define function b(param: string): string; define function c(param: boolean): boolean; type GeneralHooks<H extends (...args: any[]) => any> = [H, Parameters<H>] const obj = { a: [a, [1]] as Gene ...

Unlocking the Potential of AWS CDK: Leveraging Multiple HTTP Methods for a Single Resource

Is there a way to have a shared endpoint at /spaces with different lambda functions for each HTTP method? I thought about using a helper function addResource(path: string, method: HttpMethods, lambda: lambda.Function) { const lambdaIntegration: LambdaIn ...