3

Given this query here,

        let output = [];
        const sql = `select * from coredb.account LIMIT ${offset},${limit}`;
        let data = await sequelize.query(sql, null, {raw: true, type: sequelize.QueryTypes.SELECT});
        data.forEach((item) => {
            console.log(item['id'], item.id); // <-- output says "undefined, undefined"
        });

the data variable is indeed hydrated with the right row data when using console.log to inspect it.

But, when I try to access the individual properties, they only ever come back as undefined. This TextRow object that Sequelize seems to return the result in doesn't seem to want to let me access then explicit rows.

Just curious what i'm missing here, am I missing an option?

RedactedProfile
  • 2,748
  • 6
  • 32
  • 51

4 Answers4

3

I agree, Sequalize raw queries are not intuitive. You don't need the null or raw: true flag. Something like this should work:

let data = await sequelize.query(sql, {type: sequelize.QueryTypes.SELECT});
ow3n
  • 5,974
  • 4
  • 53
  • 51
  • 3
    LOL I just tried to vote for this answer 8 months later w/o realizing it was my own. – ow3n Nov 25 '20 at 15:28
2

When I tried this, "data" was an array of two objects, each being the query result. So, the properties can be accessed by using index [0].... e.g.

data[0].forEach((item) => {
   console.log(item['id'], item.id); // <-- output says "undefined, undefined"
});

Not yet sure WHY this occurs!

EDIT - it's because .query() should have only two arguments. Changing the call to: sequelize.query(sql, {raw: true, type: sequelize.QueryTypes.SELECT}) resulted in data being a single array (as expected).

KenOn10
  • 1,743
  • 1
  • 9
  • 10
0

Finally I was able to find the solution for it. You just need to make a new array and push data into it by finding bases on key name like this: suppose we have data in students object:

    let finalArray = new Array();
    for (var k in students ) {
      finalArray.push(students[k])
    }

 console.log(finalArray) // Normal JSON array object :)
Muhammad Waqas
  • 511
  • 6
  • 9
0
 m.sequelize.query(sql, {
          model,
          mapToModel: true
        })
          .then(model => res.status(200).send(model))
          .catch(error => res.status(400).send(error.toString())
        })
Saul Euan
  • 11
  • 3