rows.forEach is not a function

时间:2017-08-04 12:10:08

标签: javascript sql discord.js

I want to create a leaderboard for my discord users.

Here is my code:

const Discord = require('discord.js')
const sql = require("sqlite")

sql.open("../score.sqlite")

exports.run = (client, message, args) => {  
    sql.get("SELECT * FROM scores GROUP BY userId ORDER BY points DESC LIMIT 10")
        .then(rows => {
            let embed = new Discord.RichEmbed()
                .setFooter('Bot')
                .setTimestamp()
            let userArray = []
            let moneyArray = []

            rows.forEach(row => {
                userArray.push(row.userId)
                moneyArray.push(row.points)
            })

            embed.addField('Name', userArray.join('\n'), true)
            embed.addField('Money', moneyArray.join('\n'), true)
            message.channel.send({embed})
        })
}

I don't understand why forEach is no function.

1 个答案:

答案 0 :(得分:1)

假设您使用的sqlite库是this Promise-adding wrappersql.get从[{1}}返回的值的the documentation个状态:

  

如果结果集为空,[it]为undefined,否则它是包含第一行值的对象。属性名称对应于结果集的列名。

由于您的rows参数是一个Object,因此没有forEach函数。它也将是一个包含单行值的Object - 如果要从数据库中获取整个行集,则应使用sql.all而不是sql.get

以下是使用Object.keys的内容:

Object.keys(rows).forEach(key => {
    userArray.push(rows[key].userId);
    moneyArray.push(rows[key].points);
});