prisma: MongoDB: @unique constraint not working
Bug description
How to reproduce
Create a schema with @unique and add two objects with non-unique values.
Expected behavior
Throw an error
Prisma information
Environment & setup
- OS: Mac OS
- Database: MongoDB (using Azure CosmosDB with Mongo API)
- Node.js version: 15.11.0
- Prisma version: 2.21.2
prisma : 2.21.2
@prisma/client : 2.21.2
Current platform : darwin
Query Engine : query-engine e421996c87d5f3c8f7eeadd502d4ad402c89464d (at node_modules/@prisma/engines/query-engine-darwin)
Migration Engine : migration-engine-cli e421996c87d5f3c8f7eeadd502d4ad402c89464d (at node_modules/@prisma/engines/migration-engine-darwin)
Introspection Engine : introspection-core e421996c87d5f3c8f7eeadd502d4ad402c89464d (at node_modules/@prisma/engines/introspection-engine-darwin)
Format Binary : prisma-fmt e421996c87d5f3c8f7eeadd502d4ad402c89464d (at node_modules/@prisma/engines/prisma-fmt-darwin)
Default Engines Hash : e421996c87d5f3c8f7eeadd502d4ad402c89464d
Studio : 0.371.0
Preview Features : mongodb
Schema & code
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema
datasource db {
provider = "mongodb"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
previewFeatures = ["mongodb"]
}
model User {
id String @id @default(dbgenerated()) @map("_id") @db.ObjectId
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
email String @unique
}
import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();
async function main() {
await prisma.$connect();
await prisma.user.create({
data: {
email: "test@example.com",
},
});
await prisma.user.create({
data: {
email: "test@example.com",
},
});
}
main()
.catch(console.error)
.finally(() => prisma.$disconnect());
Result
➜ prismamongo npx ts-node index.ts
[
{
id: '6081b778001e4db9009f1569',
createdAt: 2021-04-22T17:50:48.444Z,
updatedAt: 2021-04-22T17:50:48.445Z,
email: 'test@example.com'
},
{
id: '6081b779001e4db9009f156a',
createdAt: 2021-04-22T17:50:49.237Z,
updatedAt: 2021-04-22T17:50:49.238Z,
email: 'test@example.com'
}
]
About this issue
- Original URL
- State: closed
- Created 3 years ago
- Reactions: 35
- Comments: 20 (7 by maintainers)
Did you run
npx prisma db push
to create the index on the database @SLTN98?here we go again
No, yeah. That was the problem!
Right now
@unique
isn’t enforced by the database. In the future, we’d like forprisma migrate
to be able to manage unique constraints.You can workaround this limitation by adding unique indices outside of Prisma (REPL, Compass, Atlas) and then writing @unique by hand to enable certain API features like findUnique in the client.
Right now I’m facing the same issue, with prisma and client in v5.12.0, someone is having this kinda problem?
it works:
npx prisma db push