CUID Not Auto-Generating
I'm trying to write a seed script to populate my database with mock data, but for whatever reason, I'm getting a null constraint error for the primary key ('_id'), even though my schema is set to autogenerate this.
It generates them just fine within my actual app, but it's not for my seed script for whatever reason.
Any ideas? (Snippets in thread.)
6 Replies
Skipping coffee for instant knowledge! Let's brew that AI answer now.
Based on the information provided in the knowledge sources, it appears that you're encountering an issue with CUID auto-generation in your seed script. This is a known issue that has been reported and discussed in Prisma's GitHub repository. Here are some insights and potential solutions:
1. CUID Generation Issue:
The error you're experiencing is likely related to a problem with CUID generation in certain environments. This issue has been reported in GitHub Issue #14864 and GitHub Issue #14870.
2. Potential Workaround:
As mentioned in one of the comments, changing the ID field from
cuid()
to autoincrement()
might resolve the issue. For example:
This workaround has been reported to work in some cases.
3. Alternative Solution for MongoDB:
If you're using MongoDB, you might consider using ObjectId
instead of cuid()
. According to the Prisma documentation on MongoDB, you can use the following schema:
This approach uses MongoDB's native ObjectId
type and might avoid the CUID generation issue.
4. Manual ID Generation:
As a last resort, you could consider manually generating IDs in your seed script. For MongoDB, you can use the bson
package to generate valid ObjectId
s:
It's important to note that the CUID generation issue seems to be environment-specific, which is why it works in your app but not in the seed script. If none of these solutions work, you might need to provide more details about your specific setup and environment for further
troubleshooting.
š¤ Alright, thanks for letting us know that there's still some help needed. A team member will reply to you shortly.
In the meantime, please let us know any additional info, questions, or which parts of the answer may need clarification.Hi š
In your ticket model, you seem to be using
id
model as both the primary key and the foreign key for the assignedTo
relation.
This causes the auto-generated cuid()
for id to be overridden (or not set) when you try to connect a user
, resulting in the null constraint violation.
The solution could be to create a separate field (commonly named something like assignedToId
) for the foreign key.
With this change, your auto-generated id
remains solely the primary key, and the optional foreign key (assignedToId) is used for the relation.Oooooh! Yeah, that makes sense. lol
Thanks!
Yep -- that fixed it! š
Glad to hear that š