sqlite 有人可以帮助我这个“参数`其中`类型UserWhereUniqueInput需要至少一个`id`参数.”错误?

ryevplcw  于 2023-08-06  发布在  SQLite
关注(0)|答案(1)|浏览(93)

我把这个控制台日志放在这里,看看接收到了什么:用户名:'aa',性别:“女性”,货物:'2',电子邮件:'a',密码:'a' }这是我遇到的错误消息:

Prisma client error: {
  timestamp: 2023-07-22T15:07:56.078Z,
  message: '\n' +
    'Invalid `prisma.user.findUnique()` invocation in\n' +
    'C:\\Users\\luiza\\Documents\\autenticação\\server.js:19:46\n' +
    '\n' +
    '  16   password,\n' +
    '  17 });\n' +
    '  18 try {\n' +
    '→ 19   const existingUser = await prisma.user.findUnique({\n' +
    '         where: {\n' +
    '           email: "a",\n' +
    '       ?   id?: Int,\n' +
    '       ?   AND?: UserWhereInput | UserWhereInput[],\n' +
    '       ?   OR?: UserWhereInput[],\n' +
    '       ?   NOT?: UserWhereInput | UserWhereInput[],\n' +
    '       ?   gender?: StringFilter | String,\n' +
    '       ?   password?: StringFilter | String,\n' +
    '       ?   username?: StringNullableFilter | String | Null,\n' +
    '       ?   admin?: BoolFilter | Boolean,\n' +
    '       ?   created_at?: DateTimeFilter | DateTime,\n' +
    '       ?   cargoId?: IntNullableFilter | Int | Null,\n' +
    '       ?   refreshTokens?: RefreshTokenListRelationFilter,\n' +
    '       ?   cargo?: CargoNullableRelationFilter | CargoWhereInput | Null,\n' +
    '       ?   posts?: PostListRelationFilter,\n' +
    '       ?   comments?: CommentListRelationFilter\n' +
    '         }\n' +
    '       })\n' +
    '\n' +
    'Argument `where` of type UserWhereUniqueInput needs at least one of `id` arguments. Available options are listed in green.',
  target: 'user.findUnique'
}
Erro: PrismaClientValidationError:
Invalid `prisma.user.findUnique()` invocation in
  16   password,
  17 });
  18 try {
→ 19   const existingUser = await prisma.user.findUnique({
         where: {
           email: "a",
       ?   id?: Int,
       ?   AND?: UserWhereInput | UserWhereInput[],
       ?   OR?: UserWhereInput[],
       ?   NOT?: UserWhereInput | UserWhereInput[],
       ?   gender?: StringFilter | String,
       ?   password?: StringFilter | String,
       ?   username?: StringNullableFilter | String | Null,
       ?   admin?: BoolFilter | Boolean,
       ?   created_at?: DateTimeFilter | DateTime,
       ?   cargoId?: IntNullableFilter | Int | Null,
       ?   refreshTokens?: RefreshTokenListRelationFilter,
       ?   cargo?: CargoNullableRelationFilter | CargoWhereInput | Null,
       ?   posts?: PostListRelationFilter,
       ?   comments?: CommentListRelationFilter
         }
       })

字符串
客户端:

document.addEventListener('DOMContentLoaded', () => {
  const createAccountBtn = document.getElementById('createAccountBtn');
  const loginBtn = document.getElementById('loginBtn');
  const cargoInput = document.getElementById('cargoInput');
  const nucleoSelection = document.getElementById('nucleoSelection');

  if (createAccountBtn) {
    createAccountBtn.addEventListener('click', handleCreateAccount);
  }

  if (loginBtn) {
    loginBtn.addEventListener('click', handleLogin);
  }

  cargoInput.addEventListener('change', () => {
    const selectedCargo = cargoInput.value;
    // Check if "Líder de Núcleo" or "Membro" is selected, and show or hide the additional selection box accordingly
    if (selectedCargo === 'lider de nucleo' || selectedCargo === 'membro') {
      nucleoSelection.style.display = 'block';
    } else {
      nucleoSelection.style.display = 'none';
    }
  });
});

async function handleCreateAccount(event) {
  event.preventDefault();

  const nameInput = document.getElementById('nameInput').value;
  const genderInput = document.getElementById('genderInput').value;
  const cargoInput = document.getElementById('cargoInput').value;
  const nucleoInput = document.getElementById('nucleoInput').value; // Get the selected nucleo value if applicable
  const emailInput = document.getElementById('emailInput').value;
  const passwordInput = document.getElementById('passwordInput').value;
  const genderValue = document.getElementById('genderValue');
  genderValue.value = genderInput;

  try {
    const response = await fetch('http://localhost:3000/register', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        username: nameInput,
        gender: genderInput,
        cargo: cargoInput,
        nucleo: nucleoInput, // Pass the selected nucleo value if applicable
        email: emailInput,
        password: passwordInput,
      }),
    });

    const data = await response.json();
    if (response.ok) {
      alert(data.message);
      redirectToFeed();
    } else {
      alert(data.error);
    }
  } catch (error) {
    console.error('Erro durante o registro:', error);
    alert('Falha no registro.');
  }
}

async function handleLogin() {
  const emailInput = document.getElementById('emaillogin').value;
  const passwordInput = document.getElementById('senhalogin').value;

  try {
    const response = await fetch('http://localhost:3000/login', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        email: emailInput,
        password: passwordInput,
      }),
    });

    const data = await response.json();
    if (response.ok) {
      // Store the JWT token received from the server securely (e.g., in local storage)
      localStorage.setItem('jwtToken', data.token);
      alert(data.message);
      setTimeout(() => {
        // Clear the input fields after a second
        document.getElementById('emaillogin').value = '';
        document.getElementById('senhalogin').value = '';
      }, 1000);
      redirectToFeed();
    } else {
      alert(data.error);
    }
  } catch (error) {
    console.error('Erro durante o login:', error);
    alert('Falha no login.');
  }
}

function redirectToFeed() {
  window.location.href = '/feedlogado.html';
}


服务器端:

const express = require('express');
const { PrismaClient } = require('@prisma/client');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const app = express();
const cors = require('cors');
const prisma = new PrismaClient();
app.use(cors());
app.use(express.json());

const jwtSecret = 'yourSecretKey';
const user = await db.collection('users').where('id', userId).get();
function generateToken(user) {
  return jwt.sign({ userId: user.id }, jwtSecret, { expiresIn: '8h' }); // Token expires in 8 hours
}

app.post('/login', async (req, res) => {
  const { email, password } = req.body;

  try {
    const user = await prisma.user.findUnique({
      where: { email: email },
      select: { id: true, email: true, password: true },
    });

    if (!user) {
      return res.status(401).json({ error: 'Credenciais inválidas' });
    }
    const passwordMatch = await bcrypt.compare(password, user.password);

    if (passwordMatch) {
      const token = generateToken(user);
      return res.status(200).json({ message: 'Login realizado com sucesso!', token, id: user.id, email: user.email });
    } else {
      return res.status(401).json({ error: 'Credenciais inválidas' });
    }
  } catch (error) {
    console.error('Erro durante o login:', error);
    res.status(500).json({ error: 'Login falhou' });
  }
});

app.post('/register', async (req, res) => {
  const { username, gender, cargo, nucleo, email, password } = req.body;

  try {
    const existingUser = await prisma.user.findUnique({
      where: { email },
    });

    if (existingUser) {
      return res.status(409).json({ error: 'Email already exists' });
    }
    const hashedPassword = await bcrypt.hash(password, 10);

    const existingCargo = await prisma.cargo.findUnique({ where: { name: cargo } });

    if (!existingCargo) {
      return res.status(404).json({ error: 'Cargo not found' });
    }

    let nucleoConnect;
    if (nucleo && !isNaN(parseInt(nucleo))) {
      const existingNucleo = await prisma.nucleo.findUnique({ where: { id: parseInt(nucleo) } });
      if (!existingNucleo) {
        return res.status(404).json({ error: 'Nucleo not found' });
      }
      nucleoConnect = { connect: { id: existingNucleo.id } };
    }

    const newUser = await prisma.user.create({
      data: {
        username,
        gender,
        cargo: {
          connect: { id: existingCargo.id },
        },
        nucleo: nucleoConnect,
        email,
        password: hashedPassword,
      },
    });

    res.status(200).json({ message: 'Conta criada com sucesso!' });
  } catch (error) {
    console.error('Erro:', error);
    res.status(500).json({ error: 'Registro falhou.' });
  }
});

const port = process.env.PORT || 3000;

const server = app.listen(port, () => {
  console.log(`Servidor iniciado em http://localhost:${port}`);
});

process.on('SIGINT', () => {
  console.log('Received SIGINT. Closing server...');
  server.close(() => {
    console.log('Server closed.');
    prisma.$disconnect().then(() => {
      console.log('Prisma client disconnected.');
      process.exit(0);
    });
  });
});

prisma.$on('error', (err) => {
  console.error('Prisma client error:', err);
});


如果有帮助的话,这是我的棱镜模型:

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

datasource db {
  provider = "sqlite"
  url      = "file:./database.db"
}

model User {
  id         Int   @id @default(autoincrement())
  gender     String   
  password   String   
  username   String?   
  email      String @unique
  refreshTokens RefreshToken[]
  admin      Boolean  @default(false)
  created_at DateTime @default(now())
  
  cargo      Cargo?   @relation(fields: [cargoId], references: [id])
  cargoId    Int?

  posts      Post[]
  comments   Comment[]
}

model Cargo {
  id         Int      @id @default(autoincrement())
  nome       String   
  nucleo     String   
  created_at DateTime @default(now())

  users      User[]
}

model Post {
  id                            Int @id @default(autoincrement())
  content                       String
  updated_at                    DateTime @updatedAt
  created_at                    DateTime @default(now())

  comment Comment[]

  userId Int
  user User @relation(fields: [userId], references: [id])
}

model Comment {

  id Int @id @default(autoincrement()) 
  content String

  postId Int
  post Post @relation(fields: [postId], references: [id])

  userId Int
  user User @relation(fields: [userId], references: [id])
  
} 
model RefreshToken {
  id          Int   @id @default(autoincrement())
  hashedToken String
  userId      Int      
  User        User     @relation(fields: [userId], references: [id], onDelete: Cascade)
  revoked     Boolean  @default(false)
  createdAt   DateTime @default(now())
  updatedAt   DateTime @updatedAt
}


我已经试过检查它的收集是否正确,但我找不到什么问题(仍在学习)

1cklez4t

1cklez4t1#

'Argument `where` of type UserWhereUniqueInput needs at least one of `id` arguments. Available options are listed in green.'

字符串
从你的堆栈跟踪,我收集的是,Prisma不知道电子邮件字段是唯一的。您的查询看起来很好。所以我认为你的问题是你需要重新生成你的prisma客户端。
根据我使用Prisma的经验,有时在将模式更改推送到DB之后,客户端不会自动重新生成。
在你的终端上试试:prisma generate

相关问题