【问题标题】:nodejs mysql verify if value existsnodejs mysql验证值是否存在
【发布时间】:2021-01-24 13:29:28
【问题描述】:

我想知道在数据库中发出请求后是否可以在 nodejs 中验证请求。

这是我的代码:

    pool.query(`SELECT * FROM * WHERE  * = ${pEvent.xxxxx};`, async (e, resultat) => {
      if(e){
        throw e
      }
      if(!resultat[0].xxxxx){
        console.log(`The item target of ${pEvent.xxxx} called ${pEvent.xxxx} doesn't exist... Do you want to create it ?`)
      }else{
        const tItemId = resultat[0].xxxx
      }

即使在这个“如果”之后,日志也说无法读取未定义的属性 'xxxxxxx'

有日志:

【问题讨论】:

  • 正如日志所说,resultat[0]undefined。无法从未定义的权限访问属性。
  • 是的,这是我在发布此问题后所看到的。对不起,谢谢你:)

标签: mysql node.js google-cloud-platform google-cloud-functions


【解决方案1】:

如果该条目不存在,则resultat 将是一个空数组,请尝试以下操作:

pool.query(`SELECT * FROM * WHERE  * = ${pEvent.xxxxx};`, async (e, resultat) => {
  if(e){
    throw e
  }
  if(!resultat || resultat.length < 1 || !resultat[0].xxxxx){
    console.log(`The item target of ${pEvent.xxxx} called ${pEvent.xxxx} doesn't exist... Do you want to create it ?`)
  }else{
    const tItemId = resultat[0].xxxx
  }
});

【讨论】:

    【解决方案2】:

    谢谢你! 这是我提出这个问题后所做的:

        pool.query(`SELECT * FROM * WHERE  * = ${pEvent.xxxxx};`, async (e, resultat) => {
          if(e){
            throw e
          }
          if(resultat[0] === undefined){
            console.log(`The item target of ${pEvent.xxxx} called ${pEvent.xxxx} doesn't exist... Do you want to create it ?`)
          }else{
            const tItemId = resultat[0].xxxx
          }
    

    它正在工作,我将使用你的解决方案,因为有更多的验证,所以发生任何崩溃的机会更少:)

    【讨论】:

      猜你喜欢
      • 2021-04-09
      • 1970-01-01
      • 2019-08-12
      • 1970-01-01
      • 1970-01-01
      • 2012-12-13
      • 1970-01-01
      • 2013-08-25
      • 1970-01-01
      相关资源
      最近更新 更多