【问题标题】:Sequelize Errors续集错误
【发布时间】:2020-06-03 04:32:54
【问题描述】:

我是使用 Sequelize 的新手,我尝试为我正在开发的 Discord Bot 游戏创建货币系统。也许我做的表格完全错了,但我认为这种方法也适用于我。我还有一些文件,例如 dbInit.js、dbObjects.js,并且在模型文件夹中我有模型/CurrencyShop.js、模型/Users.js、模型/UserItems.js,如果您需要查看其中的任何一个让我知道。

以下是错误:

(node:5916) UnhandledPromiseRejectionWarning: SequelizeDatabaseError: SQLITE_ERROR: no such table: users
    at Query.formatError (C:\Users\ryang\node_modules\sequelize\lib\dialects\sqlite\query.js:422:16)
    at Query._handleQueryResponse (C:\Users\ryang\node_modules\sequelize\lib\dialects\sqlite\query.js:73:18)
    at afterExecute (C:\Users\ryang\node_modules\sequelize\lib\dialects\sqlite\query.js:250:31)
    at Statement.errBack (C:\Users\ryang\node_modules\sqlite3\lib\sqlite3.js:16:21)
(node:5916) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:5916) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

这是我的app.js 代码:

const Discord = require('discord.js');

const client = new Discord.Client();
const { Users, CurrencyShop } = require('./dbObjects');
const { Op } = require('sequelize');
const currency = new Discord.Collection();
const PREFIX = '!';

Reflect.defineProperty(currency, 'add', {
    value: async function add(id, amount) {
        const user = currency.get(id);
        if (user) {
            user.balance += Number(amount);
            return user.save();
        }
        const newUser = await Users.create({ user_id: id, balance: amount });
        currency.set(id, newUser);
        return newUser;
    },
});

Reflect.defineProperty(currency, 'getBalance', {
    value: function getBalance(id) {
        const user = currency.get(id);
        return user ? user.balance : 0;
    },
});

client.once('ready', async () => {
    const storedBalances = await Users.findAll();
    storedBalances.forEach(b => currency.set(b.user_id, b));
    console.log(`Logged in as ${client.user.tag}!`);
});

client.on('message', async message => {
    if (message.author.bot) return;
    currency.add(message.author.id, 1);

    if (!message.content.startsWith(PREFIX)) return;
    const input = message.content.slice(PREFIX.length).trim();
    if (!input.length) return;
    const [, command, commandArgs] = input.match(/(\w+)\s*([\s\S]*)/);

    if (command === 'balance') {
        const target = message.mentions.users.first() || message.author;
        return message.channel.send(`${target.tag} has ${currency.getBalance(target.id)}????`);
    } else if (command === 'inventory') {
        const target = message.mentions.users.first() || message.author;
        const user = await Users.findOne({ where: { user_id: target.id } });
        const items = await user.getItems();

        if (!items.length) return message.channel.send(`${target.tag} has nothing!`);
        return message.channel.send(`${target.tag} currently has ${items.map(i => `${i.amount} ${i.item.name}`).join(', ')}`);
    } else if (command === 'transfer') {
        const currentAmount = currency.getBalance(message.author.id);
        const transferAmount = commandArgs.split(/ +/g).find(arg => !/<@!?\d+>/g.test(arg));
        const transferTarget = message.mentions.users.first();

        if (!transferAmount || isNaN(transferAmount)) return message.channel.send(`Sorry ${message.author}, that's an invalid amount.`);
        if (transferAmount > currentAmount) return message.channel.send(`Sorry ${message.author}, you only have ${currentAmount}.`);
        if (transferAmount <= 0) return message.channel.send(`Please enter an amount greater than zero, ${message.author}.`);

        currency.add(message.author.id, -transferAmount);
        currency.add(transferTarget.id, transferAmount);

        return message.channel.send(`Successfully transferred ${transferAmount}???? to ${transferTarget.tag}. Your current balance is ${currency.getBalance(message.author.id)}????`);
    } else if (command === 'buy') {
        const item = await CurrencyShop.findOne({ where: { name: { [Op.like]: commandArgs } } });
        if (!item) return message.channel.send(`That item doesn't exist.`);
        if (item.cost > currency.getBalance(message.author.id)) {
            return message.channel.send(`You currently have ${currency.getBalance(message.author.id)}, but the ${item.name} costs ${item.cost}!`);
        }

        const user = await Users.findOne({ where: { user_id: message.author.id } });
        currency.add(message.author.id, -item.cost);
        await user.addItem(item);

        message.channel.send(`You've bought: ${item.name}.`);
    } else if (command === 'shop') {
        const items = await CurrencyShop.findAll();
        return message.channel.send(items.map(item => `${item.name}: ${item.cost}????`).join('\n'), { code: true });
    } else if (command === 'leaderboard') {
        return message.channel.send(
        currency.sort((a, b) => b.balance - a.balance)
            .filter(user => client.users.has(user.user_id))
            .first(10)
            .map((user, position) => `(${position + 1}) ${(client.users.get(user.user_id).tag)}: ${user.balance}????`)
            .join('\n'),
        { code: true }
        );
    }
});

client.login('Njc4MTM2MzY1NTE0MzU4Nzg0.XkxHOQ.mx9sBQt0BlLlcCKn1NKP_GnbhIY');

如果有文档、视频或解释,我将不胜感激。谢谢!

【问题讨论】:

    标签: javascript node.js sequelize.js discord.js


    【解决方案1】:

    使用try-catch

     client.on('message', async message => {
        try{
    
           if (message.author.bot) return;
            currency.add(message.author.id, 1);
    
            if (!message.content.startsWith(PREFIX)) return;
            const input = message.content.slice(PREFIX.length).trim();
            if (!input.length) return;
            const [, command, commandArgs] = input.match(/(\w+)\s*([\s\S]*)/);
    
            if (command === 'balance') {
                const target = message.mentions.users.first() || message.author;
                return message.channel.send(`${target.tag} has ${currency.getBalance(target.id)}?`);
            } else if (command === 'inventory') {
                const target = message.mentions.users.first() || message.author;
                const user = await Users.findOne({ where: { user_id: target.id } });
                const items = await user.getItems();
    
                if (!items.length) return message.channel.send(`${target.tag} has nothing!`);
                return message.channel.send(`${target.tag} currently has ${items.map(i => `${i.amount} ${i.item.name}`).join(', ')}`);
            } else if (command === 'transfer') {
                const currentAmount = currency.getBalance(message.author.id);
                const transferAmount = commandArgs.split(/ +/g).find(arg => !/<@!?\d+>/g.test(arg));
                const transferTarget = message.mentions.users.first();
    
                if (!transferAmount || isNaN(transferAmount)) return message.channel.send(`Sorry ${message.author}, that's an invalid amount.`);
                if (transferAmount > currentAmount) return message.channel.send(`Sorry ${message.author}, you only have ${currentAmount}.`);
                if (transferAmount <= 0) return message.channel.send(`Please enter an amount greater than zero, ${message.author}.`);
    
                currency.add(message.author.id, -transferAmount);
                currency.add(transferTarget.id, transferAmount);
    
                return message.channel.send(`Successfully transferred ${transferAmount}? to ${transferTarget.tag}. Your current balance is ${currency.getBalance(message.author.id)}?`);
            } else if (command === 'buy') {
                const item = await CurrencyShop.findOne({ where: { name: { [Op.like]: commandArgs } } });
                if (!item) return message.channel.send(`That item doesn't exist.`);
                if (item.cost > currency.getBalance(message.author.id)) {
                    return message.channel.send(`You currently have ${currency.getBalance(message.author.id)}, but the ${item.name} costs ${item.cost}!`);
                }
    
                const user = await Users.findOne({ where: { user_id: message.author.id } });
                currency.add(message.author.id, -item.cost);
                await user.addItem(item);
    
                message.channel.send(`You've bought: ${item.name}.`);
            } else if (command === 'shop') {
                const items = await CurrencyShop.findAll();
                return message.channel.send(items.map(item => `${item.name}: ${item.cost}?`).join('\n'), { code: true });
            } else if (command === 'leaderboard') {
                return message.channel.send(
                currency.sort((a, b) => b.balance - a.balance)
                    .filter(user => client.users.has(user.user_id))
                    .first(10)
                    .map((user, position) => `(${position + 1}) ${(client.users.get(user.user_id).tag)}: ${user.balance}?`)
                    .join('\n'),
                { code: true }
                );
            }
    
        }catch(err){
         // handle all error here 
         // Like SQLITE_ERROR: no such table: users
           console.log(err)
        }
    
        });
    

    【讨论】:

    • 控制台中是否应该弹出一些新内容?我得到与以前完全相同的错误。它们也没有任何不同。
    • 第一个 UnhandledPromiseRejectionWarning 您需要处理,所以您如何处理我已经向您展示的第二个错误是“SQLITE_ERROR: no such table: users”所以请检查数据库中是否存在“users”表
    • 我的目录中有一个 database.sqlite 文件,但它是空的。我会检查这样的表吗?: SELECT 1 FROM schema_name.table_name LIMIT 0;如果是这样,我应该把它放在哪里?
    • 你使用的是哪个数据库
    • 我认为 Sequelize 会使用我制作的不同形式的表格来制作数据库。如 const newUser = await Users.create({ user_id: id, balance: amount });
    猜你喜欢
    • 2016-05-17
    • 2016-01-10
    • 1970-01-01
    • 1970-01-01
    • 2020-08-14
    • 2018-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多