Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get only dataValues from Sequelize ORM

I'm using the sequelize ORM to fetch data from a PSQL DB. However, when I retrieve something, a whole bunch of data is given. The only data I want is inside 'dataValues'. Of course, I can use object.dataValues. But, is there any other good solutions?

I'm using Sequelize 4.10

like image 254
Gijo Varghese Avatar asked Sep 23 '17 14:09

Gijo Varghese


People also ask

How do I get only dataValues from Sequelize ORM?

To get only the dataValues from Sequelize ORM, we can set the raw option to true . Model. findAll({ raw: true, //... }); to call findAll with an object with the raw property set to true to only return the dataValues in the query results.

What is raw true in Sequelize?

According to the doc : If you do not provide other arguments than the SQL, raw will be assumed to the true, and sequelize will not try to do any formatting to the results of the query.


2 Answers

Yes you can

Model.findAll({  raw: true,  //Other parameters }); 

would return just the data and not the model instance

like image 194
Shivam Avatar answered Sep 22 '22 19:09

Shivam


Sequelize wraps all it's return values in a virtual object that contains meta data. If you have an object and you just want the undecorated data values, you can unwrap them like so:

Model.findById(1).then(data => {   console.log(data.get({ plain: true })); }); 

Additionally if you just want to print out the object you can use the .toJSON method.

Model.findById(1).then(data => {   console.log(data.toJSON()); }); 
like image 44
C Deuter Avatar answered Sep 19 '22 19:09

C Deuter