Home > Mobile >  DJS MongoDB Only Updating First Document
DJS MongoDB Only Updating First Document

Time:05-17

When using one of my commands to update the guild document, it only updates the top guild document instead of the guild it gets sent in, Heres a picture to further explain it:

explanation

I want to make it so it updates in the guild it gets sent in, Heres what I have.

Code:

    run: async (interaction, client) => {

        let data = await guildSchema.findOne({
            id: interaction.guild.id
        });

      // Command:

        await guildSchema.findOneAndUpdate({
             logChannel: interaction.options.getChannel("channel").id
        });
}

I have also tried:

await data.findOneAndUpdate({

But that just returns:

TypeError: data.findOneAndUpdate is not a function

CodePudding user response:

When using .findOneAndUpdate(), it takes two arguments which are the filter and the value to change the document to. In your code, you are basically asking mongoose to search for a document where the logChannel is equal to interaction.options.getChannel("channel").id and then you are not specifying what you are updating it to. So in your case, all you have to do is add the filter and also properly receive the data because since you are using .findOneAndUpdate, it returns a document snapshot before it was changed. So your code might look something like this:

const data = await guildSchema.findOneAndUpdate({
    // Give the filter here
}, 
{
    logChannel: interaction.options.getChannel("channel").id // Update the data here
}, {
    new: true // You can optionally give this property if you want to receive the new document after the change
});

You can learn more about .findOneAndUpdate() here: Mongoose | findOneAndUpdate

CodePudding user response:

run: async (interaction, client) => {
    const data = await guildSchema.findOneAndUpdate({
        id:interaction.guild.id \\it will search for your data
    }, 
    {
        logChannel: interaction.options.getChannel("channel").id
    };
}

This should work for you

  • Related