How to get only the result from the connection query? Right now I'm using this approach. Is there a better way to do it?
const [author] = await connection.query(`SELECT * FROM authors where id=${book.authorId} LIMIT 1`)
return author.shift()
OR
const [author] = await connection.query(`SELECT * FROM authors where id=${book.authorId} LIMIT 1`)
return author[0]
If I use this approach
const result = await connection.query(`SELECT * FROM authors where id=${book.authorId} LIMIT 1`)
It returns
[ { id: 2, name: 'J. R. R. Tolkien' } ],
[
ColumnDefinition {
_buf: <Buffer 01 00 00 01 02 33 00 00 02 03 64 65 66 0b 77 64 73 2d 67 72 61 70 68 71 6c 07 61 75 74 68 6f 72 73 07 61 75 74 68 6f 72 73 02 69 64 02 69 64 0c 3f 00 ... 114 more bytes>,
_clientEncoding: 'utf8',
_catalogLength: 3,
_catalogStart: 10,
_schemaLength: 11,
_schemaStart: 14,
_tableLength: 7,
_tableStart: 26,
_orgTableLength: 7,
_orgTableStart: 34,
_orgNameLength: 2,
_orgNameStart: 45,
characterSet: 63,
encoding: 'binary',
name: 'id',
columnLength: 11,
columnType: 3,
flags: 16899,
decimals: 0
},
I don't need the fields data(the ColumnDefinition) from the connection.query
What I want is this
{ id: 2, name: 'J. R. R. Tolkien' }
without the solid bracket []
I finally found a different approach, this time I'm using nested array destructuring
const [[author]] = await connection.query(`SELECT * FROM authors where id=${book.authorId} LIMIT 1`)
return author
You can read this blog to learn more about ES6 - Destructuring