首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么`Tags.findOne();‘返回一个TypeError?

问为什么`Tags.findOne();‘返回一个TypeError?
EN

Stack Overflow用户
提问于 2022-12-04 21:18:02
回答 1查看 21关注 0票数 0

如果标签不存在,/tag [tag name]命令应该发送标记描述或消息。目前我没有在模型中的项目。当我使用任何参数运行该命令时,就会得到TypeError: Cannot read properties of undefined (reading 'findOne')。这是我的代码:

commands/tag.js

代码语言:javascript
复制
const { Tags } = require('../models/tag.js');
const { SlashCommandBuilder } = require('discord.js');

module.exports = {
    data: new SlashCommandBuilder()
        .setName('tag')
        .setDescription('Show a tag.')
        .addStringOption(option =>
            option
                .setName('name')
                .setDescription('The name of the tag')
                .setRequired(true)
        ),
    async execute(interaction) {
        const name = interaction.options.getString('name');

        const tag = Tags.findOne({where: { name: name } });

        if (tag) return interaction.reply(tag.get('description'));

        return interaction.reply('That tag doesn\'t exist!');
    }
}

模型/tag.js

代码语言:javascript
复制
module.exports = (db, DataTypes) => {
    return db.define('tags', {
        name: {
            type: DataTypes.STRING,
            unique: true,
        },
        description: DataTypes.TEXT,
    });
}

db-init.js (这是手动运行的):

代码语言:javascript
复制
const { Sequelize, DataTypes } = require('sequelize');

const db = new Sequelize({
    dialect: 'sqlite',
    storage: './database.sqlite',
});

require('./models/tag.js')(db, DataTypes);

const force = process.argv.includes('--force') || process.argv.includes('-f');

db.sync({ force }).then(async () => {
    console.log('Database synced.');

    db.close();
}).catch(console.error);

commands/addTag.js

代码语言:javascript
复制
const { Tags } = require('../models/tag.js');
const { SlashCommandBuilder } = require('discord.js');

module.exports = {
    data: new SlashCommandBuilder()
        .setName('addtag')
        .setDescription('Create a tag!')
        .addStringOption(option =>
            option
                .setName('name')
                .setDescription('The name of your tag')
                .setRequired(true)    
        )
        .addStringOption(option =>
            option
                .setName('description')
                .setDescription('The tag description')
                .setRequired(true)
        ),
    async execute(interaction) {
        const name = interaction.options.getString('name');
        const description = interaction.options.getString('description');

        try {
            const tag = await Tags.create({
                name: name,
                description: description,
            });

            return interaction.reply(`Tag \`${tag.name}\` created.`);
        } catch (error) {
            if (error.name = 'SequelizeUniqueConstraintError') return interaction.reply('That tag already exists!');

            return interaction.reply({ content: 'An error occured.', ephemeral: true });
        }
    }
}

如果标签已经存在,/addtag [tag name] [tag description]命令应该创建标记或发送消息。每当我运行这个命令时,我都不会收到任何错误,但是bot说标签已经存在了,尽管它并不存在。请有人解释一下为什么这些命令不能正常工作吗?

EN

回答 1

Stack Overflow用户

发布于 2022-12-04 21:26:59

我可以看到,您正在使用Sequelize与SQLite数据库进行交互。为了使用findOne方法,需要使用在db-init.js中创建的db对象来访问Tags模型,然后调用该对象上的findOne方法。

下面是如何修复您的tag.js文件:

代码语言:javascript
复制
const { db } = require('../db-init.js');
const { Tags } = require('../models/tag.js')(db, DataTypes); // This line is changed
const { SlashCommandBuilder } = require('discord.js');

module.exports = {
    data: new SlashCommandBuilder()
        .setName('tag')
        .setDescription('Show a tag.')
        .addStringOption(option =>
            option
                .setName('name')
                .setDescription('The name of the tag')
                .setRequired(true)
        ),
    async execute(interaction) {
        const name = interaction.options.getString('name');

        // This is the new code
        const tag = await Tags.findOne({ where: { name: name } }); // Notice the use of await here
        if (!tag) return interaction.reply('That tag doesn\'t exist!');
        return interaction.reply(tag.get('description'));
    }
}

addTag.js文件中的问题是在比较中使用SequelizeUniqueConstraintError错误名称而不是赋值。在JavaScript中,赋值运算符=不同于比较运算符==。赋值运算符为变量分配值,而比较运算符检查两个值是否相等。

下面是如何修复您的addTag.js文件:

代码语言:javascript
复制
const { db } = require('../db-init.js');
const { Tags } = require('../models/tag.js')(db, DataTypes); // This line is changed
const { SlashCommandBuilder } = require('discord.js');

module.exports = {
    data: new SlashCommandBuilder()
        .setName('addtag')
        .setDescription('Create a tag!')
        .addStringOption(option =>
            option
                .setName('name')
                .setDescription('The name of your tag')
                .setRequired(true)    
        )
        .addStringOption(option =>
            option
                .setName('description')
                .setDescription('The tag description')
                .setRequired(true)
        ),
    async execute(interaction) {
        const name = interaction.options.getString('name');
        const description = interaction.options.getString('description');

        try {
            const tag = await Tags.create({
                name: name,
                description: description,
            });

            return interaction.reply(`Tag \`${tag.name}\` created.`);
        } catch (error) {
            // This is the new code
            if (error.name === 'SequelizeUniqueConstraintError') return interaction.reply('That tag already exists!');

            return interaction.reply({ content: 'An error occured.', ephemeral: true });
        }
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74681008

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档