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()
})
CodePudding user response:
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.
CodePudding user response:
app.use(async (req,res, next)=>{
const user = await database.user.findFirst({where:{{
OR : [
{
id: req.session.userId
},
{
id: 'undefined'
}
]
}})
req.user = user
next()
})