Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop through result in sequelize

How can I get the dataValues out of the response. I have tried doing console.log(result.dataValues) but it returns undefined.

Response

[ User {
  dataValues: {
    id: 16,
    user_id: '140235016357535420',
    server_id: '535881918483398676',
    xp: 40995,
    coins: 0,
    createdAt: 2019-03-09T22
    :
    59: 09.216Z,
    updatedAt: 2019-03-09T22
    :
    59: 09.216Z
  },
},
User {
  dataValues: {
    id: 16,
    user_id: '140235016357535420',
    server_id: '535881918483398676',
    xp: 40995,
    coins: 0,
    createdAt: 2019-03-09T22
    :
    59: 09.216Z,
    updatedAt: 2019-03-09T22
    :
    59: 09.216Z
  },
},]

Query

User.findAll({
    where: {
        server_id: msg.guild.id,
    },
    limit: 2,
    order: [
        ['xp', 'DESC'],
    ],
}).then(result => {
    console.log(result);
});

Model

'use strict';
module.exports = (sequelize, DataTypes) => {
    const User = sequelize.define('User', {
        user_id: DataTypes.STRING,
        server_id: DataTypes.STRING,
        xp: DataTypes.INTEGER,
        coins: DataTypes.INTEGER,
    }, {});
    /*  User.associate = function(models) {
        // associations can be defined here
    };*/
    return User;
};
like image 673
stephendev Avatar asked Dec 24 '22 00:12

stephendev


2 Answers

That looks like an array of User objects; dataValues is a child of each User. First iterate over the array and get the objects, then extract dataValues.

for (let i = 0; i < result.length; i++)  {
  console.log(result[i].dataValues);
}

Using forEach():

result.forEach( 
  (user) => { 
    console.log(user.dataValues);
  }
);
like image 194
MBer Avatar answered Jan 03 '23 07:01

MBer


Before render/print you need to transform the Models array into array

const records = results.map(result => result.dataValues)

Details:

Out of Model search you've got an array of models like:

[ User {
  dataValues: {
    id: 16,
    user_id: '140235016357535420',
    server_id: '535881918483398676',
    xp: 40995,
    coins: 0,
    createdAt: 2019-03-09T22,
    updatedAt: 2019-03-09T22
  },
},
...]

Just "map" it like this:

const results = await User.findAll();

const records = results.map(function(result) {
            return result.dataValues
        })

and You'll get an array like this:

[
{
    id: 16,
    user_id: '140235016357535420',
    server_id: '535881918483398676',
    xp: 40995,
    coins: 0,
    createdAt: 2019-03-09T22,
    updatedAt: 2019-03-09T22
},...
]

*compact version:

const records = results.map(result => result.dataValues)
like image 31
Alexander Ivashchenko Avatar answered Jan 03 '23 06:01

Alexander Ivashchenko