使用 prisma findFirst() 时,如果值未定义,如何不返回值
我正在使用新数据库,因为我认为它使用起来很方便,但是当用户注销时,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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在这种情况下,您始终可以选择不调用数据库:
只有当 userId 未定义时,您才会调用数据库。如果未定义,您的响应将具有
user: undefined
,除非您想在这种情况下发送其他响应,但您的 user 初始值设置应该不同。You can always choose not to call DB in that case:
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.