Exploring deep nested writes within Prisma

Describing my database schema:

model User {
  id             Int       @default(autoincrement()) @id
  createdAt      DateTime  @default(now())
  email          String    @unique
  role           String    @default("user")
  sessions       Session[]
  profile        Profile?
  goalBoard      GoalBoard[]
  team           Team[]
  ...
}

model GoalBoard {
  id          Int         @default(autoincrement()) @id
  active      Boolean    // Indicates whether a goalBoard is active
  owner       User        @relation(fields: [ownerId], references: [id])
  ownerId     Int
  createdAt   DateTime    @default(now())
  goal        Goal[]
  ...
}

model Goal {
  id               Int         @default(autoincrement()) @id
  status           String
  createdAt        DateTime    @default(now())
  owner            User        @relation(fields: [ownerId], references: [id])
  ownerId          Int
  goalBoard        GoalBoard   @relation(fields: [goalBoardId], references: [id])
  goalBoardId      Int
  content          String
  goalFrequency    GoalFrequency[]
  task             Task[]
}

model Task {
  id          Int         @default(autoincrement()) @id
  status      String     // incomplete, complete
  createdAt   DateTime    @default(now())
  content     String
  goal        Goal        @relation(fields: [goalId], references: [id])
  goalId      Int
}

I am developing a mutation function that accepts an array of goal objects. Each goal object contains a nested array of task objects structured like this:

const goals = [
  {
    title: 'string',
    ...
    tasks: [
      {
        deadline: "2020/10/10",
        ...
      }
    ]
  },
  ...
]

How can I manage this data structure using Prisma2? Multiple writes and connectOrCreate logic will be needed.

Below is my unsuccessful attempt at inserting data into the database. I am testing with just one insertion and connection.

  const returnGoals = await db.goal.create({
    data: {
      content: "test goal",
      owner: {
        connect: {
          id: ctx.session!.userId,
        },
      },
      goalBoard: {
        create: { // throws a warning about incorrect usage of 'create' here
          active: true,
          owner: {
            connect: {
              id: ctx.session!.userId,
            },
          },
        },
      },
    },
  });

Answer №1

Your schema appears to be working well with this example for creating data.

import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

async function main() {
  prisma.$connect();
  const user = await prisma.user.create({
    data: {
      email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="40210021282d2524252c3937216e232f2d">[email protected]</a>',
    },
  });
  const result = await prisma.goal.create({
    data: {
      content: 'test content',
      status: 'any',
      owner: {
        connect: {
          id: user.id,
        },
      },
      goalBoard: {
        create: {
          active: true,
          owner: {
            connect: {
              id: user.id,
            },
          },
        },
      },
    },
    include: {
      owner: true,
      goalBoard: true,
    },
  });

  console.log(result);
}

main();

The output of the operation is as follows:

{
  id: 1,
  status: 'any',
  createdAt: 2020-10-04T10:53:40.956Z,
  ownerId: 1,
  goalBoardId: 1,
  content: 'test content',
  owner: {
    id: 1,
    createdAt: 2020-10-04T10:53:40.949Z,
    email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="81e0c1e0e9ece4e5e4edf8f6e0afe2eeec">[email protected]</a>',
    role: 'user'
  },
  goalBoard: {
    id: 1,
    active: true,
    ownerId: 1,
    createdAt: 2020-10-04T10:53:40.956Z
  }
}

If you are encountering any issues, it might be related to other parts of your schema implementation.

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

Removing elements in AngularJS using ngRepeat

Many have questioned how to implement item removal within the ngRepeat directive. Through my research, I discovered that it involves using ngClick to trigger a removal function with the item's $index. However, I haven't been able to find an exam ...

To make changes to an item, simply tap on the Catalog number

I'm currently facing a challenge in trying to implement a modal window that displays detailed information about a selected item based on the catalog number. The catalog number serves as the trigger to open the modal. Since I'm relatively new to a ...

Creating an infinite SVG animation loop using JavaScript

elem = document.querySelectorAll("path"); function task(i) { setTimeout(function() { elem[i].animate({fill: 'green'}, { // timing options duration: 150, iterations: 1 }); }, 150*i); } for(var i=0;i<8;i++){ task(i); } < ...

Organizing textual maps within a 2D array for rendering on an HTML5 Canvas

In my spare time, I am working on creating an HTML5 RPG game. The map is implemented using a <canvas> element with specific dimensions (512px width, 352px height | 16 tiles across, 11 tiles from top to bottom), and I'm wondering if there's ...

The performance of my JavaScript function seems to be lagging

I'm currently gathering extensive data from an API using an async function that iterates through a large amount of information using a loop. I'm sending about 100 requests and it's taking approximately 8 seconds to complete. Are there any t ...

Effective strategies for organizing component features in React

As I was reading through the React documentation, I came across the idea that using React effectively involves following the Single Responsibility Principle, meaning each component should have a specific purpose. I've already created a basic Gameboard ...

Using Node.js to execute JavaScript with imported modules via the command line

Having limited experience with running JavaScript from the command line, I am facing a situation where I need to utilize an NPM package for controlling a Panasonic AC unit, which includes a wrapper for their unofficial API. My objective is to create a sim ...

Tips for customizing the color of the current date in the angular-material datepicker

I've created a function in angular-material to disable dates two days from now, but I'm struggling to change the color of the current date if it's disabled. The issue is that when the current date is disabled, it displays in a very light blu ...

Getting an array of php data through ajax instead of using responseText in my javascript code

I am currently facing an issue with my ajax setup. My page, which contains JavaScript, calls a PHP file and receives data through xhttp.responseText. While this method works fine for handling strings, it struggles when I pass a JSON encoded array. The resp ...

Utilize the clearChart() function within Google charts in conjunction with vue-google-charts

I have integrated vue-google-charts to display various charts on my website. I want to allow users to compare different data sets, by enabling them to add or delete data from the chart. In order to achieve this functionality, I need to find a way to clear ...

Fixed width for the last column in DataTables

Here's the scenario: I have a jQuery script that loads DataTables, and I know how to set the "aoColumns" : "sWidth" parameter to fix the width of a specific column, which is working fine. However, my issue arises from having multiple tables with var ...

Why is my React Native TouchableOpacity onPress function not functioning properly?

Embarking on my journey with React Native (or any JS framework for that matter), I decided to delve into creating a simple tap game. The concept is straightforward: tap on the blue square, watch it randomly relocate, and repeat the process. Here is a snipp ...

How can I align a button right next to the table row data in HTML using Bootstrap?

Is there a way to add a button next to the table data in each row without a border? I attempted to create a new column for the button, but the border interferes with the design. I am using Bootstrap 4 for this project. Here is the HTML code: <div cl ...

Bizarre Behavior of String Comparison in Typescript When Using String.toLowerCase

As someone who is naturally curious (and has no background in JS), I have decided to take the plunge into Typescript. However, I seem to have hit a roadblock. I am trying to compare two strings but want to make it easier by first converting them to lowerca ...

Interactive Highcharts tooltip experiencing intermittent glitches during dragging

I am working with two sets of data in a line chart using Highcharts. I am trying to customize the tooltip formatter, but whenever I drag a point, the tooltip starts glitching and flickering on and off repeatedly. For reference, here is the JSFiddle link: ...

Using Regex in Javascript to locate unfinished items that start and finish with brackets

Can anyone assist me in utilizing regex to identify any incomplete items that start with {{. I have attempted to search for instances in the string that begin with {{ and are followed by letters (a-Z) but do not end with }}. However, my attempts always re ...

How can I set up an additional "alert" for each form when making an AJAX request?

let retrieveLoginPasswords = function (retrieveForgottenPasswords, checkLoginStatus) { $(document).ready(function () { $('#login,#lostpasswordform,#register').submit(function (e) { e.preventDefault(); $.ajax({ type: &quo ...

What is the process for retrieving the values of response headers in JavaScript?

After receiving a response from Axios, I need to retrieve the values from the Response Header. https://i.sstatic.net/lEcWg.png In the image above, I am specifically looking to extract the value of Location which is found in the Response Header. Could you ...

Tips for dynamically passing parameters to functions in JavaScript?

Looking for a solution to dynamically receive input from the user in my function: divResize = { myDiv:function(width, height) {...} } divResize.myDiv(100,400); I want to make these numbers interactive and changeable based on user input. How can I achie ...

Inquiries about utilizing setTimeout with backbone.js and effectively managing timeouts

One of the questions I have is related to clearing timeouts using clearTimeout(content.idTimeout) for a specific idTiemout. But how can I clear all timeouts at once? Here is the model I am working with: var ContentModel = Backbone.Model.extend({ URL: "htt ...