DEV Community

Cover image for Editing and Deleting with MongoDB (Discord.JS)
w6
w6

Posted on • Edited on

Editing and Deleting with MongoDB (Discord.JS)

Welcome 👋

First of all, if you haven't seen Part 1, you should read it or you may be confused. We're going to be using the same database that we created!

Editing & Saving Data

So, you want to edit data and save it to your database. Well, this is how you do that.

We're going to be changing the server's "key" to a new one! This is just an example but, you can use this for your own bot's functionalities.

Let's say that right now the server's "key" is ExampleLol123 and we want to change it to SuperSecretKey, this is how!

Start off by finding the server's entry by using the "FindOne" function.

Schema.findOne({ Guild: interaction.guild.id }, async (err, data) => {

});

Enter fullscreen mode Exit fullscreen mode

Now that we've found the server's entry, let's change it's "key" to SuperSecretKey.

In the code below, we'll check if there is any data for the server then if there is, we'll change it.

if (data) {
  data["SpecialKey"] = "SuperSecretKey";
}
Enter fullscreen mode Exit fullscreen mode

Finally, let's save it!

data.save();
Enter fullscreen mode Exit fullscreen mode

Wasn't that easy? ☝️ Let's move on to deleting data!

Deleting Data 🗑

Let's say you want to delete a server's data (eg, if the bot was kicked from the server and you don't want to use up space), this is how!

We'll be using the handy findOneAndDelete function for this part of the tutorial. Basically, you'll find the entry and delete it all in 1 function! 😱

Schema.findOneAndDelete({ Guild: interaction.guild.id }, async (err, data) => {
});
Enter fullscreen mode Exit fullscreen mode

If there's an error, we'll log that in the console 👇

if (err) {
   console.log(`❌Looks like there's an error: ${err}`);
}
Enter fullscreen mode Exit fullscreen mode

Otherwise, if there isn't an error and everything is good, we'll make sure to log in the console that the operation was successful! ✅

else {
  console.log(`🍃 That was quick. Data deleted successfully! ✅`);
}
Enter fullscreen mode Exit fullscreen mode

Learning More...

You've just learned how to 👀

  • Edit Data
  • Delete Data
  • and.. save it!

But if you want to learn more, please leave a ❤️ or a Comment 💬 to motivate me to make more of these tutorials!

Thank you for reading! 😃

Top comments (0)