node.jssequelize.js

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

Solution

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