{"id":16305,"library":"bot-database","title":"Bot Database Module","description":"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.","status":"active","version":"3.4.5","language":"javascript","source_language":"en","source_url":null,"tags":["javascript","typescript"],"install":[{"cmd":"npm install bot-database","lang":"bash","label":"npm"},{"cmd":"yarn add bot-database","lang":"bash","label":"yarn"},{"cmd":"pnpm add bot-database","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Core Object Data Modeling (ODM) library for MongoDB integration. Used for schema definition, validation, and interaction with the database.","package":"mongoose","optional":false},{"reason":"Used internally for making HTTP requests, potentially for interacting with external APIs, bot platforms, or webhooks.","package":"node-fetch"},{"reason":"Used for generating unique identifiers (UUIDs) for database entries or internal object tracking.","package":"uuid4"}],"imports":[{"note":"While the README shows CommonJS `require`, modern TypeScript and Node.js projects increasingly use ES Modules (ESM). For type safety and better tooling, prefer the ESM `import` syntax. The CJS `require` might still work, but ESM is recommended for new code.","wrong":"const { DataBase } = require('bot-database');","symbol":"DataBase","correct":"import { DataBase } from 'bot-database';"},{"note":"This is a type import for configuring the DataBase instance, ensuring correct typings when initializing the module.","symbol":"IDataBaseOptions","correct":"import type { IDataBaseOptions } from 'bot-database';"},{"note":"Assuming the library exports specific Mongoose schemas (e.g., for users) from a subpath. This allows direct access to pre-defined data structures for bot-related entities.","symbol":"UserSchema","correct":"import { UserSchema } from 'bot-database/models';"}],"quickstart":{"code":"import { DataBase } from 'bot-database';\nimport mongoose from 'mongoose';\n\n// Define a simple Mongoose schema for a bot user\nconst userSchema = new mongoose.Schema({\n  userId: { type: String, required: true, unique: true },\n  username: { type: String, required: true },\n  guildId: { type: String },\n  points: { type: Number, default: 0 },\n  lastSeen: { type: Date, default: Date.now },\n});\n\nconst UserModel = mongoose.model('User', userSchema);\n\nasync function runBotDatabase() {\n  const mongoUri = process.env.MONGO_URI ?? 'mongodb://localhost:27017/mybotdb';\n\n  try {\n    // Initialize the bot database module\n    const db = new DataBase({\n      mongoUri: mongoUri,\n      models: { User: UserModel } // Pass in Mongoose models if the library expects them\n    });\n\n    await db.connect(); // Connect to MongoDB\n    console.log('Successfully connected to MongoDB!');\n\n    // Example: Create or update a user\n    const userId = '123456789';\n    const username = 'TestBotUser';\n\n    let user = await UserModel.findOneAndUpdate(\n      { userId },\n      { username, $inc: { points: 1 } },\n      { upsert: true, new: true }\n    );\n\n    console.log('User created/updated:', user);\n\n    // Example: Find a user\n    const foundUser = await UserModel.findOne({ userId });\n    console.log('Found user:', foundUser);\n\n  } catch (error) {\n    console.error('Database operation failed:', error);\n  } finally {\n    await mongoose.disconnect(); // Disconnect from MongoDB\n    console.log('Disconnected from MongoDB.');\n  }\n}\n\nrunBotDatabase();","lang":"typescript","description":"Demonstrates connecting to MongoDB, initializing the `bot-database` module, defining a Mongoose schema, and performing basic CRUD operations (create/update and find) for a bot user."},"warnings":[{"fix":"For new projects or TypeScript-enabled projects, prefer `import { DataBase } from 'bot-database';`. If forced to use CommonJS for the main application, dynamic `import()` might be an option, but it complicates asynchronous execution.","message":"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.","severity":"gotcha","affected_versions":">=3.0.0"},{"fix":"Always check the `bot-database` `package.json` for its internal Mongoose dependency range (if visible) or its documentation for recommended `mongoose` versions. Ensure your project's `mongoose` peer dependency aligns to avoid conflicts. Refer to Mongoose's official compatibility matrix.","message":"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.","severity":"breaking","affected_versions":">=3.0.0"},{"fix":"Ensure `db.connect()` is awaited before any database operations and `mongoose.disconnect()` is called in a `finally` block or on application shutdown to gracefully close connections. Use proper error handling with `try...catch`.","message":"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.","severity":"gotcha","affected_versions":">=3.0.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Verify that your MongoDB instance is running and accessible from your application's environment. Check the `mongoUri` for correctness (host, port, database name).","cause":"The MongoDB server is not running or is inaccessible at the specified URI.","error":"MongooseServerSelectionError: connect ECONNREFUSED"},{"fix":"Change `const { DataBase } = require('bot-database');` to `import { DataBase } from 'bot-database';`.","cause":"You are attempting to use CommonJS `require()` syntax within an ES Module (`.mjs` file or `\"type\": \"module\"` in `package.json`) environment.","error":"ReferenceError: require is not defined in ES module scope"},{"fix":"Ensure `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.","cause":"The `DataBase` instance was not properly initialized or returned `undefined`, or `new DataBase()` was called without a valid configuration object if required.","error":"TypeError: Cannot read properties of undefined (reading 'connect')"}],"ecosystem":"npm"}