如何遍历结果导致续集

时间:2019-03-15 23:25:55

标签: node.js sequelize.js

如何从响应中删除dataValues。我尝试做console.log(result.dataValues),但返回的结果不确定。

响应

[ 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
  },
},]

查询

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

模型

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

2 个答案:

答案 0 :(得分:1)

看起来像一个User对象数组; dataValues是每个用户的子级。首先遍历数组并获取对象,然后提取"http.proxyStrictSSL": false

dataValues

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

forEach()

答案 1 :(得分:0)

渲染/打印之前,您需要将Models数组转换为array

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

详细信息:

在“模型搜索”中,您有一系列模型,例如:

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

就像这样“映射”它:

const results = await User.findAll();

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

您将得到一个像这样的数组:

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

*紧凑版:

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