Error encountered: The input value does not correspond to any valid input type for the specified field in Prisma -Seed

When trying to run the seed command tsx prisma/seed.ts, it failed to create a post and returned an error.

→ 6 await prisma.habit.create( Validation failed for the query:

Unable to match input value to any allowed input type for the field. Parse errors: [Query parsing/validation error at 
Mutation.createOneHabit.data.HabitCreateInput.created_at
: A value is required but not set., Query parsing/validation error at 
Mutation.createOneHabit.data.HabitUncheckedCreateInput.created_at
: A value is required but not set.]
at Mutation.createOneHabit.data at Object.handleRequestError (/Users/luistigre/www/nlw/nlw/aulas/server/node_modules/@prisma/client/runtime/index.js:31941:13) at Object.handleAndLogRequestError (/Users/luistigre/www/nlw/nlw/aulas/server/node_modules/@prisma/client/runtime/index.js:31913:12) at Object.request (/Users/luistigre/www/nlw/nlw/aulas/server/node_modules/@prisma/client/runtime/index.js:31908:12) at PrismaClient._request (/Users/luistigre/www/nlw/nlw/aulas/server/node_modules/@prisma/client/runtime/index.js:32994:16) at main (/Users/luistigre/www/nlw/nlw/aulas/server/prisma/seed.ts:6:5) { code: 'P2009', clientVersion: '4.9.0', meta: { query_validation_error: 'Unable to match input value to any allowed input type for the field. Parse errors: [Query parsing/validation error at
Mutation.createOneHabit.data.HabitCreateInput.created_at
: A value is required but not set., Query parsing/validation error at
Mutation.createOneHabit.data.HabitUncheckedCreateInput.created_at
: A value is required but not set.]', query_position: 'Mutation.createOneHabit.data' }, batchRequestIdx: undefined }

An error occurred while executing the seed command: Error: Command failed with exit code 1: tsx prisma/seed.ts

SCHEMA.PRISMA


generator client {
provider = "prisma-client-js"
}

datasource db {
provider = "sqlite"
url      = env("DATABASE_URL")
}

generator erd {
provider = "prisma-erd-generator"
}

model Habit {
id         String   @id @default(uuid())
title      String
created_at DateTime

dayHabits DayHabit[]
weekDays  HabitWeekDays[]

@@map("habits")
}

model HabitWeekDays {
id       String @id @default(uuid())
habit_id String
week_day Int

habit Habit @relation(fields: [habit_id], references: [id])

@@unique([habit_id, week_day])
@@map("habit_week_days")
}

model Day {
id        String     @id @default(uuid())
date      DateTime
dayHabits DayHabit[]

@@unique([date])
@@map("days")
}

model DayHabit {
id       String @id @default(uuid())
day_id   String
habit_id String

day   Day   @relation(fields: [day_id], references: [id])
habit Habit @relation(fields: [habit_id], references: [id])

@@unique([day_id, habit_id])
@@map("day_habits")
}

SEED.TS FILE


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

const prisma = new PrismaClient()

async function main() {
await prisma.habit.create({
data: {
title: 'Drink 2L of water',
created_at: new Date('2023-01-10T00:00:00:000z')
}
})

}


main()
.then(async () => {
await prisma.$disconnect()
})
.catch(async (e) => {
console.error(e)
await prisma.$disconnect()
process.exit(1)
})

PACKAGE.JS

 "prisma": {
"seed": "tsx prisma/seed.ts"
}

I expected the data to be successfully saved into the database.

Answer №1

Consider making this adjustment:

created_at: new Date('2023-01-22T00:00.000z')

Change it to this:

created_at: new Date('2023-01-22')

Alternatively, use this for the current date:

created_at: new Date()

The function new Date('2023-01-22T00:00.000z') produces an invalid date. You can validate this by logging in your browser's console or executing a TS file using node.

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

After installing TypeScript community stubs, WebStorm is unable to locate the module

Recently, I tried to incorporate the ramda library into my project and went ahead to install its TypeScript community stubs in WebStorm. https://i.stack.imgur.com/fCFG8.png Despite my efforts, I encountered an error that stated — Cannot find module &a ...

Using React and TypeScript, open the initial tab from a mapped array with an accordion component

{accordion.map(accordionItem => ( <AccordionItem key={accordionItem.title} text={accordionItem.text} title={accordionItem.title} ></AccordionItem> ...

Designing a TypeScript class with unique properties and attributes

I have an idea for creating a versatile class named Model. Here's what I have in mind: export class Model { _required_fields: Array<string> = []; _optional_fields?: Array<string> = []; constructor(params: Dictionary<string& ...

Automatically select a value in MUI AutoComplete and retrieve the corresponding object

I recently set up a list using the MUI (v4) Select component. I've received a feature request to make this list searchable due to its extensive length. Unfortunately, it appears that the only option within MUI library for this functionality is the Au ...

Proper utilization of react-hook-form in conjunction with TypeScript and material-ui to display error messages efficiently

Currently, I am using a combination of react-hook-form with typescript and material-ui. My goal is to pass the error message as a helperText to the TextField. I attempted to achieve this by utilizing helperText={errors.email?.message} however, TypeScript ...

Exploring Typescript code through a practical example with reference to Uniswap's implementation

On the Uniswap website, I came across some code on the Swap page that caught my attention. You can find the code snippet in question at line 115 of the Uniswap GitHub repository. const { trade: { state: tradeState, trade }, allowedSlippage, cur ...

Retrieving the chosen option from a dropdown menu using AngularJS

<tr (click)="onRowClick(myDropDownList.value)"> <td> <select #myDropDownList (click)="$event.stopPropagation()" (change)="onChange($event.target.value)"> <option *ngFor="let n of numbers" [value]="n">{{n}}</option> </se ...

Utilize the power of GitHub Actions to seamlessly deploy your Next.js Prisma application to V

Currently, I am developing a Next.js 13 website on GitHub Actions and then deploying it statically to Vercel. The site employs Prisma, but during the runtime logs analysis on Vercel, I encountered an error: 2022-12-12T01:07:00.163Z 2022-12-12T01:07:00.196 ...

Angular's FormGroup for reactive forms is a powerful feature that allows for

Why am I unable to type in the input field before setting a value? html <form action="" [formGroup]="titleForm"> <input class="note-title" type="text" formControlName="title"> </form> ...

Executing the command `subprocess.run("npx prettier --write test.ts", shell=True)` fails to work, however, the same command runs successfully when entered directly into the terminal

Here is the structure of my files: test.py test.ts I am currently trying to format the TypeScript file using a Python script, specifically running it in Command Prompt on Windows. When I execute my python script with subprocess.run("npx prettier --w ...

What is the best way to implement callbacks with $http in Typescript?

When making my $http call, I am looking for the most adaptable way to handle all the parameters returned in the .success and .error functions. Here is an example of what my $http call looks like: this.$http({ url: "/api/x", method: "GET" }) .success((? ...

Optimal strategies for managing server-side validation/errors in Angular applications

Back in the day, I used to retrieve HTTP responses with a TypeScript object. validateTokenHttp(token: string): Observable<User> { return this.http.get<User>(`${environment.api}/auth/verifyToken/${token}`); } Sometimes it would return a Us ...

"Receiving an error message stating 'Was expecting 1 parameter, received 2' while trying to pass a useState function in TypeScript

I am encountering an issue with a component where I pass a useState setter to a utility function: export interface IData { editable: string[]; favourited: string[]; } const [data, setData] = useState<IData | undefined>(undefined) useEffect(() = ...

Angular: Issue encountered when accessing nested properties within an interface due to reading properties of undefined

Encountering difficulties with utilizing nested property interface. //Food Interface (food.interface.ts)// export interface Food { name: string; quantity?: string; description?: string; nutrients?: { calories?: number; protein?: number; carbs?: ...

Confirm the identity of a user by checking their email against the records stored in a MySQL database

I am currently working on creating a user verification system using email that is stored in a mySql database and utilizing express JS. The user is required to input their email before filling out any other forms. If the email is not found in the email tabl ...

When using tsdx with React, null values can prevent proper usage of hooks

Recently, I attempted to develop a React TypeScript component using tsdx for compilation and encountered a roadblock while debugging. The package appears to be successfully published and installed without any errors. However, when trying to use it, I consi ...

Generating a custom type in Typescript based on specific array keys

Imagine I have a structure like this: export interface MyObject { id: number title: string } and then I create an array as shown below: const myArray: MyObject[] = [ { id: 2358, title: 'Item 1' }, { id: 85373, title: &a ...

Formulate a Generic Type using an Enum

I'm currently working on a project that involves creating a generic Type using enums. Enum export enum OverviewSections { ALL = 'all', SCORE = 'score_breakdown', PERFORMANCE = 'performance_over_time', ENGAGEMENT ...

Angular // binding innerHTML data

I'm having trouble setting up a dynamic table where one of the cells needs to contain a progress bar. I attempted using innerHTML for this, but it's not working as expected. Any suggestions on how to approach this? Here is a snippet from my dash ...

TypeScript does not properly validate the types of defaultProps

When working with TypeScript 3.0, I consulted the documentation at https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-0.html The recommendation is to use static defaultProps: Pick<Props, "name"> as an explicit type annotation ...