Simple MongoDB Database Setup for Discord.JS (Replit)

September 3, 2022


Here’s an easy implementation of MongoDB in a Discord.JS bot built on Replit! Be sure to follow the steps closely or you might miss something.



Step 1

Create a “models” folder in your bot, we’ll use this to store all the databases in.



Step 2

IMPORTANT: Create a environment variable called mongodb and put your database’s connection URI in there. It should look something like this: mongodb+srv://username:[email protected]/?retryWrites=true&w=majority

Don’t use the example I provided, put your own, it won’t work. If you don’t have a MongoDB, you can create on at MongoDB.

In your index.js file, include this:

const mongoose = require('mongoose');

mongoose.connect(process.env.mongodb, { useNewUrlParser: true, useUnifiedTopology: true }).then(console.log('Connected to Mongodb.'));
Enter fullscreen modeExit fullscreen mode

In the code above, we’re connecting to your MongoDB database.



Step 3

Back to the models folder. Create a file in there with any name you want, I’ll use “keys.js” for my example.

In the file, import the schema which you’ll use later on.

const mongo = require('mongoose');

const Schema = new mongo.Schema({
  Guild: Number,
  SpecialKey: String
});
Enter fullscreen modeExit fullscreen mode

Here, we’re specifying the basic schema that we’ll use for the database. You can change this to fit your bot’s functionalities.

Finally, export the schema as follows:

module.exports = mongo.model('yourdatabasename', Schema);
Enter fullscreen modeExit fullscreen mode

Add that to the bottom of the file! 😃

If you don’t know how to make your own schema, you can view some examples here.



Step 4

This is the final step! Go to your bot’s command cog you want to use the database in and follow these steps:

Import the database:

const Schema = require('../../models/keys.js'); // Example
Enter fullscreen modeExit fullscreen mode

Then in your command, you can fetch values as follows:

Schema.findOne({ Guild: interaction.guild.id }, async (err, data) => {
  if (data) {
    respond({"content": `This server's special key is: ${data["SpecialKey"]}!`});
  } else {
    new Schema ({
      Guild: interaction.guild.id,
      SpecialKey: "Examples ✨"
    }).save()

    respond({"content": `Woah! This server doesn't have a key yet 👀 I've just set yours to the default key instead!`});
  }
});
Enter fullscreen modeExit fullscreen mode



Editing and Deleting Data

If this post does well, I’ll do a follow-up one with a tutorial on how to edit data, delete data and more.

➡️ If you found this post helpful, please give it a 👍, Thank you!

⚡️ Do you want an advanced invite tracker in your discord server? Consider adding my verified bot, Ayami!



Source link

Comments 0

Leave a Reply

Your email address will not be published. Required fields are marked *