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
- Create a free account at mongodb.com/atlas
- Create a free M0 cluster
- Add a database user with a password
- Whitelist
0.0.0.0/0in Network Access to allow your bot server to connect - 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.