TypeError: Cannot read properties of undefined
Hello, I'm trying to seed my database using my action, but it's saying it cannot read the properties of undefined pointing to the entity type:
///
return context.entities.TipoEPI.create(....
///
my entity in main.wasp:
entity TipoEPI {=psl
id Int @id @default(autoincrement())
nome String
descricao String
epi EPI[]
psl=}
/* .... */
action createTipoEPI {
fn: import {createTipoEPI} from "@src/epis/actions",
entities: [TipoEPI]
}
my code in the actions.js:
export const createTipoEPI = (args, context) => {
return context.entities.TipoEPI.create({
data: {
nome: args.nome,
descricao: args.descricao
}
})
}
a fragment of the seeding function the calls the action:
export const seedTipoEPI = async (prisma) => {
const results = [];
const csvFilePath = resolve(__dirname, '../../../../src/seeds/tipoepi.csv');
fs.createReadStream(csvFilePath)
.pipe(csv())
.on('data', (data) => results.push(data))
.on('end', async () => {
for (const item of results) {
await createTipoEPI(prisma, {
nome: item.type
});
}
console.log('Successfully seeded TipoEPI data.');
});
}
I don't understant why it's saying the property is undefined if even the vscode extension was autocompleting the code the way it is.
Any idea?
I'm not using this action anywhere else because it only gets a huge predefined list of values to use in relation with other entities.
Thanks!20 Replies
Hi @danimiclos. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
----------------------
It seems like you're trying to use the
createTipoEPI
action within your seed function. However, the context
object that is passed to the action function is not the same as the prisma
object that is passed to the seed function. The context
object is created by Wasp and includes properties like user
and relevant Prisma entities like Project
(source (https://discord.com/channels/686873244791210014/1216119302244270181)).
In your seed function, you're passing prisma
as the first argument to createTipoEPI
, but in the action function definition, context
is the second argument. This could be why context.entities.TipoEPI
is undefined
.
You could try modifying your seed function to pass an object as the second argument to createTipoEPI
, with entities
as a property of that object:
And then in your action function, you can access TipoEPI
from context.entities
:
This way, you're passing the prisma.tipoEPI
instance to the action function, which should allow you to call create
on it.
Please note that this is a workaround and might not be the best practice. The best way to seed the database using Actions is still under discussion in the Wasp community (source (https://github.com/wasp-lang/wasp/issues/569)).
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------
Sorry @danimiclos, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist:
Perhaps try again in 15mins?@kapa.ai
I've changed the code in the seed function at
await createTipoEPI({...
and now I got almost the same error:
[ Db ] > [email protected] bundle
[ Db ] > rollup --config --silent
[ Db ]
[ Db ] Current directory: /home/daniel/projects/waspprojects/safemate/.wasp/out/server
[ Db ] Running seed: seedTipoEPI
[ Db ] Current directory: /home/daniel/projects/waspprojects/safemate/.wasp/out/server
[ Db !] /home/daniel/projects/waspprojects/safemate/src/seeds/dbEpiTypeSeed.js:27
[ Db !] entities: { TipoEPI: prisma.tipoEPI }
[ Db !] ^
[ Db !]
[ Db !]
[ Db !] TypeError: Cannot read properties of undefined (reading 'tipoEPI')
[ Db !] at CsvParser.<anonymous> (/home/daniel/projects/waspprojects/safemate/src/seeds/dbEpiTypeSeed.js:27:41)
[ Db !] at CsvParser.emit (node:events:519:28)
[ Db !] at endReadableNT (node:internal/streams/readable:1696:12)
[ Db !] at process.processTicksAndRejections (node:internal/process/task_queues:82:21)
[ Db !]
[ Db !] Node.js v21.6.2
any other idea? Maybe for some reason the TipoEPI isn't initialyzing?
Hello @kapa.ai are you there now?Wohooo @danimiclos, you just became a Waspeteer level 1!
Let me check the knowledge base for you. One moment! :books:
----------------------
Yes, I'm here. How can I assist you with Wasp today?
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------
Sorry @danimiclos, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist:
Perhaps try again in 15mins?
@kapa.ai
I've changed the code in the seed function at await createTipoEPI({... and now I got almost the same error:
[ Db ] > [email protected] bundle
[ Db ] > rollup --config --silent
[ Db ]
[ Db ] Current directory: /home/daniel/projects/waspprojects/safemate/.wasp/out/server
[ Db ] Running seed: seedTipoEPI
[ Db ] Current directory: /home/daniel/projects/waspprojects/safemate/.wasp/out/server
[ Db !] /home/daniel/projects/waspprojects/safemate/src/seeds/dbEpiTypeSeed.js:27
[ Db !] entities: { TipoEPI: prisma.tipoEPI }
[ Db !] ^
[ Db !]
[ Db !]
[ Db !] TypeError: Cannot read properties of undefined (reading 'tipoEPI')
[ Db !] at CsvParser.<anonymous> (/home/daniel/projects/waspprojects/safemate/src/seeds/dbEpiTypeSeed.js:27:41)
[ Db !] at CsvParser.emit (node:events:519:28)
[ Db !] at endReadableNT (node:internal/streams/readable:1696:12)
[ Db !] at process.processTicksAndRejections (node:internal/process/task_queues:82:21)
[ Db !]
[ Db !] Node.js v21.6.2
any other idea? Maybe for some reason the TipoEPI isn't initialyzing? (edited)
Let me check the knowledge base for you. One moment! :books:
----------------------
The error message suggests that
prisma.tipoEPI
is undefined
. This could be due to a few reasons:
1. The prisma
object passed to the seed function does not have a tipoEPI
property. This could be because the TipoEPI
model is not defined in your Prisma schema or there is a typo in the model name.
2. The prisma
object itself is undefined
. This could happen if there was an error when initializing the Prisma client.
To debug this issue, you could try the following steps:
1. Check your Prisma schema (schema.prisma
) to make sure the TipoEPI
model is defined correctly.
2. Log the prisma
object in your seed function to see if it's undefined
or if it's missing the tipoEPI
property:
3. If prisma
is undefined
, there might be an issue with how you're initializing the Prisma client. If prisma.tipoEPI
is undefined
, there might be an issue with your Prisma schema or the way you're importing the TipoEPI
model.
Remember that in Prisma, model names are case-sensitive and should match the model name in your Prisma schema. If your model is named TipoEPI
in the schema, you should access it with prisma.tipoEPI
, not prisma.TipoEPI
or any other case variation.
If none of these steps help, please provide more information about your Prisma setup and I'll do my best to assist you further.
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------
Sorry @danimiclos, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist:
Perhaps try again in 15mins?@kapa.ai using
console.log(prisma)
returns undefined.
my whole seeding code is as follow:
import { createTipoEPI } from "../epis/actions";
import fs from 'fs';
import csv from 'csv-parser';
import { fileURLToPath } from 'url';
import { dirname, resolve } from 'path';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
export const seedTipoEPI = async (prisma) => {
console.log(
Current directory: ${process.cwd()});
const results = [];
const csvFilePath = resolve(__dirname, '../../../../src/seeds/tipoepi.csv');
console.log(prisma);
fs.createReadStream(csvFilePath)
.pipe(csv())
.on('data', (data) => results.push(data))
.on('end', async () => {
for (const item of results) {
await createTipoEPI({
nome: item.type
}, {
entities: { TipoEPI: prisma.tipoEPI }
});
}
console.log('Successfully seeded TipoEPI data.');
});
}
seedTipoEPI().catch((e) => {
console.error(e);
prisma.$disconnect();
});
Is there any way I should initialize prisma on the wasp db seed command? When I dot wasp start the the prisma client must be initializing since I have access to the database and actions.Let me check the knowledge base for you. One moment! :books:
----------------------
The
prisma
object is typically initialized when you start your Wasp application with wasp start
. However, in the context of a seed script, you might need to initialize it manually.
In your seed script, you can import and initialize the Prisma client like this:
Then, you can use the prisma
object to interact with your database. Don't forget to disconnect the Prisma client at the end of your script with prisma.$disconnect()
to ensure that the Node.js event loop is not being blocked (source (https://www.prisma.io/docs/concepts/components/prisma-client/working-with-prismaclient/connection-management)).
Here's how your updated seed script might look:
Please note that this is a workaround and might not be the best practice. The best way to seed the database using Actions is still under discussion in the Wasp community (source (https://github.com/wasp-lang/wasp/issues/569)).
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------
Sorry @danimiclos, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist:
Perhaps try again in 15mins?@kapa.ai I've changed my code again commenting the action call just to check if there is a prisma.tipoEPI:
import { PrismaClient } from '@prisma/client'
import { createTipoEPI } from "../epis/actions";
import fs from 'fs';
import csv from 'csv-parser';
import { fileURLToPath } from 'url';
import { dirname, resolve } from 'path';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const prisma = new PrismaClient()
export const seedTipoEPI = async (prisma) => {
console.log(
Current directory: ${process.cwd()});
const results = [];
const csvFilePath = resolve(__dirname, '../../../../src/seeds/tipoepi.csv');
console.log(prisma.tipoEPI);
console.log('Successfully seeded TipoEPI data.');
// });
prisma.$disconnect()
}
seedTipoEPI().catch((e) => {
console.error(e);
prisma.$disconnect();
});
But I'm still getting errors at the end, even without use any action. The result now is:
[ Db !] TypeError: Cannot read properties of undefined (reading 'tipoEPI')
[ Db !] at seedTipoEPI (/home/daniel/projects/waspprojects/safemate/src/seeds/dbEpiTypeSeed.js:20:24)
[ Db !] at <anonymous> (/home/daniel/projects/waspprojects/safemate/src/seeds/dbEpiTypeSeed.js:40:3)
[ Db !] at ModuleJob.run (node:internal/modules/esm/module_job:218:25)
[ Db !] at async ModuleLoader.import (node:internal/modules/esm/loader:323:24)
[ Db !] at async loadESM (node:internal/process/esm_loader:28:7)
[ Db !] at async handleMainPromise (node:internal/modules/run_main:120:12)
Let me check the knowledge base for you. One moment! :books:
----------------------
The error message suggests that
prisma.tipoEPI
is undefined
. This could be because the TipoEPI
model is not defined in your Prisma schema or there is a typo in the model name.
In Prisma, model names are case-sensitive and should match the model name in your Prisma schema. If your model is named TipoEPI
in the schema, you should access it with prisma.tipoEPI
, not prisma.TipoEPI
or any other case variation.
Here are a few things you could check:
1. Make sure the TipoEPI
model is defined in your Prisma schema (schema.prisma
).
2. Ensure that the model name is spelled and cased correctly. If the model is named TipoEPI
in the schema, you should use prisma.tipoEPI
.
3. Try logging prisma
to see if it's initialized correctly:
If prisma
is undefined
, there might be an issue with how you're initializing the Prisma client. If prisma.tipoEPI
is undefined
, there might be an issue with your Prisma schema or the way you're importing the TipoEPI
model.
If none of these steps help, please provide more information about your Prisma setup and I'll do my best to assist you further.
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------
Sorry @danimiclos, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist:
Perhaps try again in 15mins?@sodic something for you to pick up tomorrow
Hey @danimiclos, still having trouble with this?
If so, I'll check it out tomorrow.
In the meantime, please check our instructions for asking questions (they pop up when you press the button to ask a new question).
Most notably, it's better to paste large code blocks as blocks (rather than inline code). This makes it easier for both kapa.ai and me to understand you 🙂
This:
Instead of this:
export const createTipoEPI = (args, context) => {
return context.entities.TipoEPI.create({
data: {
nome: args.nome,
descricao: args.descricao
}
})
}
Hello @sodic, thank you for your attention. I'm happy to inform you that the seeding process is now working as expected. The issue was resolved by importing the PrismaClient. Initially, I did not try this solution as I was following the example provided in the documentation where there was no mention of importing the PrismaClient in the code.
I apologize for the code block formatting. I often forget how to format code when pasting it. Here's my solution, I hope it looks good in the chat:
Thanks a lot for the update @danimiclos! And yeah, the code looks great, no worries 🙂
@martinsos This looks pretty familiar (i.e., the prisma client being uninitialized in user seed scripts), but I can't find the issue that talks about it. Do you maybe know what I'm referring to?
If not, I'll dig deeper
@sodic yeah it also rings a bell to me like we potentially had some similar issue before, but I also am not sure where to exactly find it right now.
@danimiclos , quick look at the code from my side:
- You don't need to do
const prisma = new PrismaClient()
, Kapa bot misguided you there (it can be like that).
Your seed functions recieve prisma
as the first argument, already initialized for you.
- You also don't need the last part: seedTipoEPI().catch((e) => { ... });
, that is redundant.
So, your code should work when looking something like this:
I also removed that additional prisma.$disconnect()
.
If you go with code like this, does it work? If you do instead get an error, please paste the whole error message and we will try to figure it out from there.
Oh, and did you register your seeding function in main.wasp
file, via app.db.seeds
? Please also copy that part of code, so we can see how you did that, and finally also tell us how you run your seed from the CLI, which command do you use.@martinsos sorry, I didn't saw your reply. I will be back on this project tomorrow and, then I wil be able to test and give you a response. Thanks!
Wohooo @danimiclos, you just became a Waspeteer level 2!
Awesome, looking forward to it!
Hello @martinsos, it's working now with your code. Thank you!
Awesome, nice to hear that @danimiclos !
DO you have any ideas what we could have done on our side to make this easier for you? Maybe something we could improve in docs, or in Wasp itself?