使用 prisma findFirst() 时,如果值未定义,如何不返回值

发布于 2025-01-20 20:26:37 字数 629 浏览 7 评论 0原文

我正在使用新数据库,因为我认为它使用起来很方便,但是当用户注销时,req.session.userId将是未定义的。因此,当我将 findFirst() 函数与 { where : req.session.userId } 一起使用时。如果 req.session.userId 未定义。 findFirst() 仍然返回表中的第一条记录。 如何解决当 req.session.userId 未定义时 findFirst() 不得返回值的问题。

它有点类似于 MySQL 查询命令。

SELECT * FROM user WHERE id = req.session.userId;

我的 Prisma 查询代码。

app.use(async (req,res, next)=>{
  let user

  user = await database.user.findFirst({where:{
    id: req.session.userId
  }})

  req.user = user
  next()
})

I'm working at the new database because it's convenient to use in my opinion, but when the user is logged out, req.session.userId will be undefined. So when I'm use findFirst() function with { where : req.session.userId }. If the req.session.userId is undefined. The findFirst() is still return the first record the the table.
How do I fix that findFirst() must not return the value when req.session.userId is undefined.

It's kind of equivalent to the MySQL Query Command.

SELECT * FROM user WHERE id = req.session.userId;

My Prisma query code.

app.use(async (req,res, next)=>{
  let user

  user = await database.user.findFirst({where:{
    id: req.session.userId
  }})

  req.user = user
  next()
})

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

情绪失控 2025-01-27 20:26:37

在这种情况下,您始终可以选择不调用数据库:

app.use(async (req,res, next)=>{
  let user

  user = req.session.userId && await database.user.findFirst({where:{
    id: req.session.userId
  }})

  req.user = user
  next()
})

只有当 userId 未定义时,您才会调用数据库。如果未定义,您的响应将具有 user: undefined,除非您想在这种情况下发送其他响应,但您的 user 初始值设置应该不同。

You can always choose not to call DB in that case:

app.use(async (req,res, next)=>{
  let user

  user = req.session.userId && await database.user.findFirst({where:{
    id: req.session.userId
  }})

  req.user = user
  next()
})

Only if userId is not undefined you will call your database. And in case it is undefined, your response will have user: undefined, unless you want to send some other response in this case, but the your initial value setting of user should be different.

浪推晚风 2025-01-27 20:26:37
app.use(async (req,res, next)=>{
const  user = await database.user.findFirst({where:{{
   OR : [
     {
   id: req.session.userId
 },
{
   id: 'undefined'
 }
   ]
}})

 req.user = user
 next()
})
app.use(async (req,res, next)=>{
const  user = await database.user.findFirst({where:{{
   OR : [
     {
   id: req.session.userId
 },
{
   id: 'undefined'
 }
   ]
}})

 req.user = user
 next()
})
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文