简体   繁体   中英

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()
})

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.

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

 req.user = user
 next()
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM