提问人:Dandraghas 提问时间:10/22/2023 最后编辑:Dandraghas 更新时间:10/22/2023 访问量:78
字段的唯一约束失败:('email')
Unique constraint failed on the fields: (`email`)
问:
当我尝试注册用户时,它失败并显示:
PrismaClientKnownRequestError:
Invalid `prisma.user.create()` invocation:
Unique constraint failed on the fields: (`email`)
at Cn.handleRequestError (/home/dandraghas/Documents/Projects/auth/node_modules/@prisma/client/runtime/library.js:123:6817)
at Cn.handleAndLogRequestError (/home/dandraghas/Documents/Projects/auth/node_modules/@prisma/client/runtime/library.js:123:6206)
at Cn.request (/home/dandraghas/Documents/Projects/auth/node_modules/@prisma/client/runtime/library.js:123:5926)
at async l (/home/dandraghas/Documents/Projects/auth/node_modules/@prisma/client/runtime/library.js:128:9968)
at async file:///home/dandraghas/Documents/Projects/auth/routes/post.js:45:21 {
code: 'P2002',
clientVersion: '5.4.2',
meta: { target: [ 'email' ] }
}
我尝试了 2 次,它抛出一个错误,但实际上在数据库中创建了两个用户:
TABLE "User";
id | email | password | username
----+----------------------+--------------------------------------------------------------+------------
1 | [email protected] | [REDACTED] | user
3 | [email protected] | [REDACTED] | test
(2 rows)
下面是架构:
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("POSTGRES_PRISMA_URL")
directUrl = env("POSTGRES_URL_NON_POOLING")
}
model User {
id Int @id @default(autoincrement())
email String @unique
username String @unique
password String
}
下面是注册用户的函数:
router.post("/post/register", async (req, res) => {
if (!req.body.email || !req.body.password || !req.body.username) {
return res.status(400).json({ message: "Please provide email, password, and username" });
}
const existingUser = await prisma.user.findUnique({
where: {
email: req.body.email,
},
});
if (existingUser) {
return res.status(400).json({ message: "Email already exists" });
}
const hashedPassword = await bcrypt.hash(req.body.password, 12);
const newUser = await prisma.user.create({
data: {
email: req.body.email,
username: req.body.username,
password: hashedPassword,
},
});
console.log(`Successfully created User: ${req.body.email}`);
return res.status(201).json({ message: "User created successfully", user: newUser });
});
它甚至使用数据库中的条目响应客户端,但随后无一例外地崩溃。
我尝试使用Prisma重置和重新生成数据库,但仍然不起作用。
编辑:经过调查,我发现它跳过了一个用户ID,当我创建一个新用户时,应该有ID 2,但它跳到了3,也许这里有问题?
答: 暂无答案
评论