#db.query is not a function

29 messages · Page 1 of 1 (latest)

terse lark

Hello, I have a problem with my db when I make my command I have this error that appears, db.query is not a function

const { SlashCommandBuilder, EmbedBuilder } = require("discord.js");
const db = require("../../utils/database");

module.exports = {
  data: new SlashCommandBuilder()
    .setName("lock")
    .setDescription("Verrouille le salon")
    .addChannelOption((option) =>
      option.setName("salon").setDescription("Salon").setRequired(true)
    )
    .addStringOption((option) =>
      option
        .setName("reason")
        .setDescription("Raison du lock")
        .setRequired(true)
    ),
  async execute(interaction) {

    try {

      console.log(db)
      const channel = interaction.options.getChannel("salon");
      const reason = interaction.options.getString("reason");

      await db.query(`SELECT * FROM lockchannel WHERE GuildID = "${interaction.guild.id}" AND channel = "${channel.id}"`, (err, req) => {
      
        if(req.length > 1) {
          return interaction.reply({
            content: `> Le salon ${channel} est déjà verrouillé ![no](https://cdn.discordapp.com/emojis/1199859706424987740.webp?size=128 "no").`,
            ephemeral: true,
          });
        }
        if(req.length < 1) {

          const role = interaction.guild.roles.cache.find(
            (role) => role.name === "@everyone"
          );
    
          channel.permissionOverwrites.edit(role, {
            SendMessages: false,
          });

          const msg = new EmbedBuilder()
          .setTitle(
            ":cadenasverrouille: || Salon verrouillé"
          )
          .setColor("Red")
          .setFields(
            {
              name: `__**![profil](https://cdn.discordapp.com/emojis/1148950147829604402.webp?size=128 "profil") || Vérrouillé par**__`,
              value: `<@${interaction.user.id}>`,
            },
            {
              name: `__**![outilcrayon](https://cdn.discordapp.com/emojis/1199812967068356638.webp?size=128 "outilcrayon") || Raison**__`,
              value: `${reason}`,
            }
          )
          .setFooter({
            text: "Katsuki",
            iconURL: interaction.guild.iconURL()
              ? interaction.guild.iconURL()
              : "https://imgur.com/a06O1Wn.png",
          })
          .setTimestamp();

  
          db.query(`INTERT INTO lockchannel (GuildID, userID, channel, reason) VALUES ("${interaction.guild.id}", "${interaction.user.id}", "${channel.id}", "${reason.replace(/"/g, '\\"')}")`)

          channel.send({ embeds: [msg] });
        }
      
      })


    } catch (e) {
      console.log(e);
    }
  },
};
pulsar wharfBOT
  • Consider reading #how-to-get-help to improve your question!
  • Explain what exactly your issue is.
  • Post the full error stack trace, not just the top part!
  • Show your code!
  • Issue solved? Press the button!
  • Marked as resolved by OP
shadow lily

what is in the file ../../utils/database

terse lark
const mysql = require("mysql")

module.exports = async () => {

  let db = mysql.createConnection({
    host: "localhost",
    user: "root",
    port: "3306",
    password: "",
    database: "discord"

  })

  db.connect(err => {
    if(err) throw err;
    console.log("[INFO] Database Connected !");
  })

  return db;
}```
shadow lily

ok well, you're exporting a function

and a function doesn't typically have other functions as properties

terse lark

So what do I do?

shadow lily

call the function that you export, it will return db

or export db itself, not a function that returns db

personally i would use an ORM like sequelize, but if you want to interact with the connector directly then you can just do what you're doing now

terse lark

Sorry but how can i do that ? I'm new to js 😅

I've tried sequelize but I can't do what I want to do

shadow lily

what issues did you have with sequelize?

terse lark

I wanted to retrieve information from the DB but couldn't without a copy of it.

shadow lily

a copy of what?

terse lark

For example, I wanted to search in my DB for a channel id to send a message there, but if I didn't have a copy of the id to search in my DB for the channel, it wouldn't work.

So i want to try mysql because i have a friend who uses mysql but when i asked him he saw no error

shadow lily

🤔 but you'll run into the same issue anyway

you need to know the ID to search for the ID

terse lark

No, with mysql I succeeded to do what I wanted in a function, but when I want to do it in my command, it gives me this error

shadow lily

i mean, ultimately it just the difference between

db.query(`SELECT * FROM lockchannel WHERE GuildID = "${interaction.guild.id}" AND channel = "${channel.id}"`, (err, req) => { ... });

and

LockChannels.findOne({ where: { GuildID: interaction.guild.id, channel: channel.id } });
terse lark

Yes but with sequelize we need the id of the channel for search in db

shadow lily

what's the difference? you need the ID anyway, looking at both lines of code

anyway, all you need to do is call the function you import

first of all, call the import something like makeConnection:

const makeConnection = require("../../utils/database");

then call it later:

const db = await makeConnection();
db.query(...);
terse lark

thanks it work ;)

And so I don't know I didn't succeed with sequelize

Maybe it's just me :')

shadow lily
terse lark

Where should I put this?