2

I'm trying to create a discord bot, specifically the wedding team.

I am using a MongoDB database. Now everything works and is saved, but there is one problem, the data is saved for the second and third rounds, etc.

That is, the checks that I added do not work. I am trying to find data through const exists = Marry.findOne({ message.author.id });, everything finds, I checked with console log.

But when I try to validate it just doesn't work. if (exists == message.author.id) { return message.channel.send("You are already married!"); }

What could be the problem? Help me please!

Maybe instead userID: message.author.id i just need to find for the value message.author.id. Is it possible?

const { Command } = require("discord.js-commando");
const mongoose = require("mongoose");

mongoose.connect('mongodb+srv://admon:admin@cluster0.sobzp.mongodb.net/dbname?retryWrites=true&w=majority');

//create Schema

const marrySchema = new mongoose.Schema({
    userID: {
        type: mongoose.SchemaTypes.String,
        required: true
    },

    userMarryID: {
        type: mongoose.SchemaTypes.String,
        required: true
    },

    userPartnerID: {
        type: mongoose.SchemaTypes.String,
        required: true
    }
});

const Marry = mongoose.model('Marry', marrySchema);

module.exports = class MarryCommand extends Command {
    constructor(client) {
        super(client, {
            name: "marry",
            memberName: "marry",
            group: "test",
            description: "Marry the mentioned user",
            guildOnly: true,
            args: [{
                key: "userToMarry",
                prompt: "Please select the member you wish to marry.",
                type: "member",
            }, ],
        });
    }

    run(message, { userToMarry }) {
        const exists = Marry.findOne({ userID: message.author.id });
        const married = Marry.findOne({ userID: userToMarry.id });

        if (!userToMarry) {
            return message.channel.send("Please try again with a valid user.");
        }
        if (exists == message.author.id) {
            return message.channel.send("You are already married!");
        }
        if (married == userToMarry.id) {
            return message.channel.send("This user is already married!");
        }
        if (userToMarry.id == message.author.id) {
            return message.channel.send("You cannot marry yourself!");
        }
        if (exists != message.author.id && married != userToMarry.id) {
            message.channel.send(
                    `**Important announcement!**
    
    ${message.author} makes a marriage proposal ${userToMarry}
    
    Are you ready to get married?`
                )
                .then((message) => {
                    message.react("")
                    .then(() => message.react(""))
                    .catch(() => {
                        //code
                    });
                    message.awaitReactions((reaction, user) =>
                        user.id == userToMarry.id && (reaction.emoji.name == "" || reaction.emoji.name == ""), {
                            max: 1,
                            time: 10000,
                            errors: ["time"]
                        }
                    ).then((collected) => {
                        const reaction = collected.first();
                        if (reaction.emoji.name === "") {
                            return message.channel.send("I think **no**...");
                        }
                        if (reaction.emoji.name === "") {
                                const createdExists = new Marry({
                                    userID: message.author.id,
                                    userMarryID: message.author.id,
                                    userPartnerID: userToMarry.id
                                });
                                createdExists.save().catch(e => console.log(e));

                                const createdMarried = new Marry({
                                    userID: userToMarry.id,
                                    userMarryID: userToMarry.id,
                                    userPartnerID: message.author.id
                                });
                                createdMarried.save().catch(e => console.log(e));

                            message.channel.send(`${message.author} and ${userToMarry} now married!!`)
                                .catch(() => {
                                    message.reply(
                                        "No reaction after 10 seconds, operation canceled"
                                    );
                                });
                        }
                    }).catch(() => {});
                }).catch(() => {});
        }
    }
};
  • Did called somewhere `mongoose.connect('mongodb://connection-uri-here');`? – Leandro Lima Mar 30 '22 at 13:07
  • @LeandroLima connection-uri is this? `mongodb+srv://admon:admin@cluster0.sobzp.mongodb.net/dbname?retryWrites=true&w=majority` –  Mar 30 '22 at 13:22
  • exactly, you should call `mongoose.connect()` with this connection uri. And try to not post that URI everywhere because it contains the user and password of your database, and people can access that :p – Leandro Lima Mar 30 '22 at 15:04
  • @LeandroLima this is not real data, I did everything like this, but I get an error `An error occurred while running the command: ReferenceError: Marry is not defined` –  Mar 30 '22 at 15:22
  • Hmm... Got it, I think instead of doing `module.exports = mongoose.model('Marry', marrySchema);` you need to put it into a variable or a constant like: `const Marry = mongoose.model('Marry', marrySchema);`, in this way you're defining Marry – Leandro Lima Mar 30 '22 at 15:40
  • @LeandroLima Still getting another error( `An error occurred while running the command: TypeError: Cannot read property 'id' of undefined` –  Mar 30 '22 at 16:00
  • I think now you have to see what is undefined maybe `message.author` or `message.userToMarry` – Leandro Lima Mar 30 '22 at 16:04
  • @LeandroLima Initially, the database is empty, so how can I do these checks differently? –  Mar 30 '22 at 16:06
  • I think you're already doing checks for the database objects, I think the error is on the `message` argument of the `run` function, that maybe is not setting either the `author` or `userToMarry` prop. If you want to do check over these guys you can do `Marry.findOne({ userID: message.author ? message.author.id : null });` (same thing for `userToMarry` – Leandro Lima Mar 30 '22 at 17:27
  • @LeandroLima Now there are no errors, but nothing is saved in the database, and no checks work, as if these functions do not work `const exists = Marry.findOne` –  Mar 30 '22 at 17:51
  • What is printed when you do a `console.log(message)`? – Leandro Lima Mar 30 '22 at 18:21
  • @LeandroLima the data of the one who sent the message, the command itself, and the data of the user we indicate, there is a very long message –  Mar 30 '22 at 18:35
  • @LeandroLima I made a mistake, all checks work, saving to the database does not work. Maybe I did something wrong in saving? –  Mar 30 '22 at 18:36
  • `const exists = Mary.findOne` and `const married = Marry.findOne`.... are these in fact promises and not synchronous? – The Bomb Squad Mar 31 '22 at 12:17
  • @TheBombSquad all the conditions below `exists` and `married` work for me, and the command itself too, the only thing is that data on married users is not saved to the database –  Mar 31 '22 at 12:23
  • but this is my first experience of creating a bot, and maybe there are some other ways, but I don't know yet –  Mar 31 '22 at 12:27

2 Answers2

0

So I think you're having an async issue in your code. The query itself should work just fined. However, I suggest you move exists and married outside of run. Maybe paste them under the MongoDB connection and find a way to pass the message.

const Marry = mongoose.model('Marry', marrySchema);
const exists = Marry.findOne({ message.author.id });
const married = Marry.findOne({ userToMarry.id });

If that doesn't work, another thing you could try is making the findOne queries async inside the run method, like this:

const married = await db.collection("yourcollectioname").findOne({ message.author.id });
const exists = await db.collection("yourcollectioname").findOne({ userToMarry.id });
ZombieChowder
  • 1,187
  • 12
  • 36
0

Try using async for the run function. Next, await to search for data in the database.

You get something like this:

async run(message, { userToMarry }) {
const exists = await Marry.findOne({ userID: message.author.id });

Further, in the check, we add userID to exists to compare exactly the numbers:

if (exists?.userID === message.author.id) { return message.channel.send("You are already married!"); }

? this is in case there is no data and exists = null

Same for userToMarry