Simple MongoDB Database Setup for Discord.JS (Replit)
Tags: javascript, node, discord, mongodb
Published: 2022-09-03 04:13:35

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.

#### Requirements

> **1.** You'll need `discord.js` installed of-course, I prefer using v14 but you can use an older version if you haven't upgraded yet.
> **2.** Lastly, you'll need a [`MongoDB`](https://mongodb.com) database set up. Make sure you have `0.0.0.0` whitelisted in the IP addresses so it will work with Replit.

**🍃 MongoDB** is a free database on the cloud that we'll use in this tutorial. It's very easy-to-use and it has a free tier!

## Step 1

Create a `"models"` folder in your bot, we'll use this to store all the databases in.
![Folder](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/46aaymy4felqh2tshbec.png)



## 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:password@cluster0.clusters.mongodb.net/?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](https://mongodb.com/)_.

In your **index.js** file, include this:

```js
const mongoose = require('mongoose');

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

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.

```js
const mongo = require('mongoose');

const Schema = new mongo.Schema({
  Guild: Number,
  SpecialKey: String
});
```

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:

```js
module.exports = mongo.model('yourdatabasename', Schema);
```

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](https://mongoosejs.com/docs/guide.html).

## 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:

```js
const Schema = require('../../models/keys.js'); // Example
```

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

```js
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!`});
  }
});
```

## 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. 

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