0

Background

I'm making a simple website with node and typescript. I installed MySQL module to communicate with a database.

Problem

I'm trying to get data from DB, but I don't know how to determine what type the result should have. For example,

const sql = `SELECT metaValue FROM ${this.table} WHERE metaKey = '${key}'`;
const result = await this.pool.query(sql);
console.log(result);

in this case, the result is [ RowDataPacket { metaValue: 'map-79.jpg' } ]. How can I get map-79.jpg from the result? What type the result should be?

0

3 Answers 3

2

it will return Object Array :

const sql = `SELECT metaValue FROM ${this.table} WHERE metaKey = '${key}'`;
const result = await this.pool.query(sql);
console.log(result);
result.forEach(row => {
    console.log(row.metaValue)
})

Or you Can create array by using map

let imgArray = result.map(row => { return row.metaValue });
console.log(imgArray);
Sign up to request clarification or add additional context in comments.

1 Comment

It returns Query type. I cannot use foreach or map because it is not Array type.
0

@Pushpendra Kumar was right. But we need type guard before using result as Array like below.

const sql = `SELECT metaValue FROM ${this.table} WHERE metaKey = '${key}'`;
let rows = await this.pool.query(sql);
if ( Array.isArray(rows) ) {
  return rows[0].metaValue
}

Comments

0

I use let records: youDefinedInterface[] = [].slice.call(result, 0); to cast the Query type to a normal array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.