Home > Net >  How to format an SQL result?
How to format an SQL result?

Time:02-04

so i'm new to SQL (And programming in general) and i'm building something that require a SQL select. The selection works fine, if a certain value exists on the DB, it returns me this:

[ RowDataPacket { id: 1, token: 'cuf0njqu4qmur5docha5ka', used: 0 } ]

If it doesn't exist, it gives me this:

[]

But i'm using Node JS and I can't get it to compare [ ] with null, is there any way I can set this empty array as 0 or false?

The code:

const sql = `SELECT * FROM tokens WHERE token = '${token}' AND used = 0`

    pool.query(sql, function(err, data) {
        if (err) {
            console.log(err)
            return
        }
        const valid = data
        console.log(data)

        if (valid !== null) {
            const used = `UPDATE tokens SET used = 1 WHERE token = '${token}'`
            pool.query(used, function(err, data) {
                console.log("The token is valid!")
                if (err) {
                    console.log(err)
                    return
                }
            })
        } else {
            console.log("The token is not valid.")
        }
    })

CodePudding user response:

looks like data is an empty array [] which is still a 'truthy' value.

you can see truthyness of an expression using !! (not not)

console.log(!![]) 
> true

console.log(!!0)
> false

you can check the length property of an array.

const valid = data && data.length;

or

const valid = !!data.length
  •  Tags:  
  • Related