Bot Database Module
The `bot-database` package, currently at stable version 3.4.5, provides a data persistence layer specifically designed for bot projects. It primarily integrates with MongoDB through the Mongoose ORM, abstracting common database operations to simplify data management within bot applications. This library likely offers pre-defined schemas or convenience methods tailored for typical bot data, such as user profiles, guild configurations, and command states, differentiating it from general-purpose Mongoose wrappers. Its focus on bot development aims to reduce boilerplate and streamline database interactions for bot creators. The release cadence is not explicitly stated but the version number suggests active development.
Common errors
-
MongooseServerSelectionError: connect ECONNREFUSED
cause The MongoDB server is not running or is inaccessible at the specified URI.fixVerify that your MongoDB instance is running and accessible from your application's environment. Check the `mongoUri` for correctness (host, port, database name). -
ReferenceError: require is not defined in ES module scope
cause You are attempting to use CommonJS `require()` syntax within an ES Module (`.mjs` file or `"type": "module"` in `package.json`) environment.fixChange `const { DataBase } = require('bot-database');` to `import { DataBase } from 'bot-database';`. -
TypeError: Cannot read properties of undefined (reading 'connect')
cause The `DataBase` instance was not properly initialized or returned `undefined`, or `new DataBase()` was called without a valid configuration object if required.fixEnsure `new DataBase({ /* options */ })` is correctly implemented and its return value is assigned before attempting to call methods like `connect()`. Review required configuration options for the `DataBase` constructor.
Warnings
- gotcha The README's `require` import example is CommonJS. While the library ships TypeScript types, implying ESM compatibility, directly using `require` in an ES Module project (e.g., `"type": "module"` in `package.json`) will result in a runtime error.
- breaking Mongoose version compatibility is crucial. Mismatched Mongoose versions between `bot-database`'s internal dependency and your project's direct `mongoose` peer dependency can lead to unexpected errors or deprecated features.
- gotcha Failure to properly handle Mongoose connection and disconnection can lead to open database connections or unhandled promise rejections, especially in serverless or short-lived bot environments.
Install
-
npm install bot-database -
yarn add bot-database -
pnpm add bot-database
Imports
- DataBase
const { DataBase } = require('bot-database');import { DataBase } from 'bot-database'; - IDataBaseOptions
import type { IDataBaseOptions } from 'bot-database'; - UserSchema
import { UserSchema } from 'bot-database/models';
Quickstart
import { DataBase } from 'bot-database';
import mongoose from 'mongoose';
// Define a simple Mongoose schema for a bot user
const userSchema = new mongoose.Schema({
userId: { type: String, required: true, unique: true },
username: { type: String, required: true },
guildId: { type: String },
points: { type: Number, default: 0 },
lastSeen: { type: Date, default: Date.now },
});
const UserModel = mongoose.model('User', userSchema);
async function runBotDatabase() {
const mongoUri = process.env.MONGO_URI ?? 'mongodb://localhost:27017/mybotdb';
try {
// Initialize the bot database module
const db = new DataBase({
mongoUri: mongoUri,
models: { User: UserModel } // Pass in Mongoose models if the library expects them
});
await db.connect(); // Connect to MongoDB
console.log('Successfully connected to MongoDB!');
// Example: Create or update a user
const userId = '123456789';
const username = 'TestBotUser';
let user = await UserModel.findOneAndUpdate(
{ userId },
{ username, $inc: { points: 1 } },
{ upsert: true, new: true }
);
console.log('User created/updated:', user);
// Example: Find a user
const foundUser = await UserModel.findOne({ userId });
console.log('Found user:', foundUser);
} catch (error) {
console.error('Database operation failed:', error);
} finally {
await mongoose.disconnect(); // Disconnect from MongoDB
console.log('Disconnected from MongoDB.');
}
}
runBotDatabase();