'How to not return a value when using prisma findFirst() where the value is undefined
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()
})
Solution 1:[1]
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.
Solution 2:[2]
app.use(async (req,res, next)=>{
const user = await database.user.findFirst({where:{{
OR : [
{
id: req.session.userId
},
{
id: 'undefined'
}
]
}})
req.user = user
next()
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Lazar Nikolic |
| Solution 2 | Moein T |
