Get only dataValues from Sequelize ORM

故事扮演 提交于 2019-12-03 00:00:45

Yes you can

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

would return just the data and not the model instance

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());
});

Finally I found answer after searching a lot. you should do something like this

const users = await db.users.findAll({})
   .map(el => el.get({ plain: true })) // add this line to code

source: github issue

The problem occurs only when I log it using:

console.log(Model.findAll());

If I save it to a variable, I can directly access objects inside without using "dataValues"

To clarify Masoud Tavakkoli's answer (which is not immediately clear on that github answer): using element.get({ plain: true }) returns an array of objects with each attribute key:value pairs.

If you just want an array of one specific attribute's values (eg user ids) instead of objects, you can use something like this:

const users = await User.findAll({
    attributes: ["id"], 
    where: {} // Your filters here
}).map(u => u.get("id")) // [1,2,3]

Nika Kasradze's answer actually achieves the same outcome as a middle-step; using the JSON stringifier generates the same array output. It's possible this is faster than mapping, but I'm not sure.

const users = await User.findAll({
    attributes: ["id"], 
    where: {} // Your filters here
})
const userIds = JSON.stringify(users)) // [1,2,3]

For nested entities this stupid workaround works for me:

let row = await Model.findOne({
     include: [ /*your includes here*/ ]
});
row = JSON.parse( JSON.stringify(row, null, 4) );

Somehow JSON.stringify(row, null, 4) removes all the extra stuff and pretends the dataValues property of the object is the object itself. Then the JSON.parse(...) puts the object back together.

EDIT:

so apparently I'm new to typescript so I didn't need this at all. the console.log(row) printing huge object got me confused. I miss good ol' c# times :'(

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!