我想为我的不和谐用户创建一个排行榜。

这是我的代码:

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


我不明白为什么forEach没有功能。

最佳答案

假设您使用的sqlite库为this Promise-adding wrapper,则the documentation表示从sql.get返回的值:


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


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

这是使用Object.keys的样子:

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

09-26 01:21
查看更多