New to CraftNodes? Use code WELCOME10 at checkout for 10% off your first month.

Back to Blog

May 13, 2026

Discord Bot with Database: Using MongoDB Atlas for Persistent Data

Learn how to use MongoDB Atlas with your Discord bot for persistent data storage. Works with discord.js and discord.py bots hosted on CraftNodes.


Why Use a Database?

Storing bot data in memory means it is lost when the bot restarts. A database lets you persist user levels, economy balances, warnings, settings, and any other data across restarts.

MongoDB Atlas Setup

  1. Create a free account at mongodb.com/atlas
  2. Create a free M0 cluster
  3. Add a database user with a password
  4. Whitelist 0.0.0.0/0 in Network Access to allow your bot server to connect
  5. Get your connection string from the Connect menu

Using Mongoose with discord.js

const mongoose = require('mongoose');

mongoose.connect(process.env.MONGODB_URI)
  .then(() => console.log('Connected to MongoDB'))
  .catch(err => console.error(err));

Creating a Schema

const userSchema = new mongoose.Schema({
  userId: String,
  guildId: String,
  xp: { type: Number, default: 0 },
  level: { type: Number, default: 0 }
});

Storing the Connection String

Set MONGODB_URI as an environment variable in your CraftNodes Pterodactyl panel under the Startup tab. Never hardcode credentials in your code.


All posts

CraftNodes Blog