Skip to main content

Overview

The Telegram Subscription Manager uses MongoDB as its database with Prisma ORM for type-safe database access. This guide covers setting up MongoDB Atlas (cloud-hosted MongoDB) and initializing your database schema.

Prerequisites

  • A valid email address
  • Credit card for verification (free tier available, no charges)

Create MongoDB Atlas Account

1

Sign Up for MongoDB Atlas

  1. Go to MongoDB Atlas
  2. Click “Try Free” or “Sign Up”
  3. Sign up with:
    • Google account (recommended)
    • Email and password
    • GitHub account
  4. Complete the registration
2

Create Organization and Project

After signing up, Atlas will prompt you to create an organization and project:
  1. Organization Name: Your company or personal name
  2. Project Name: telegram-subscription-bot (or your preferred name)
  3. Click “Next” or “Create Project”
Organizations can contain multiple projects. One project is sufficient for this bot.

Create Database Cluster

1

Build a Cluster

  1. Click “Build a Database” or “Create”
  2. Choose deployment option:
2

Configure Security - Database Access

Create a database user:
  1. Go to Database Access (in the Security section of sidebar)
  2. Click “Add New Database User”
  3. Choose authentication method:
    • Authentication Method: Password (recommended)
  4. Set credentials:
    • Username: botuser (or your preferred username)
    • Password: Click “Autogenerate Secure Password” and copy it
  5. Database User Privileges:
    • Select “Read and write to any database”
  6. Click “Add User”
Save your password securely! You’ll need it for the connection string and cannot retrieve it later.
3

Configure Security - Network Access

Allow connections from Vercel:
  1. Go to Network Access (in the Security section)
  2. Click “Add IP Address”
  3. Choose “Allow Access from Anywhere”:
    • IP Address: 0.0.0.0/0
    • Comment: Vercel and development
  4. Click “Confirm”
0.0.0.0/0 allows connections from any IP, which is required for Vercel’s serverless functions. MongoDB Atlas still requires username/password authentication.
For additional security in production, you can use MongoDB’s Atlas CLI to restrict to specific Vercel IPs, but 0.0.0.0/0 is standard and safe when using strong credentials.
4

Get Connection String

  1. Go to Database (in the Deployment section)
  2. Click “Connect” on your cluster
  3. Choose “Connect your application”
  4. Select:
    • Driver: Node.js
    • Version: 4.1 or later
  5. Copy the connection string:
mongodb+srv://botuser:<password>@cluster0.xxxxx.mongodb.net/?retryWrites=true&w=majority
  1. Replace <password> with your actual password (the one you generated/saved earlier)
  2. Add database name before the ?:
mongodb+srv://botuser:[email protected]/telegram_bot?retryWrites=true&w=majority
Ensure you:
  • Replace <password> with actual password
  • Add database name (e.g., telegram_bot)
  • No spaces in the connection string

Configure Environment Variable

Add the connection string to your environment variables:

Local Development

Add to .env.local:
.env.local
DATABASE_URL="mongodb+srv://botuser:[email protected]/telegram_bot?retryWrites=true&w=majority"
Wrap the URL in quotes to handle special characters in the password.

Vercel (Production)

Add to Vercel environment variables:
  1. Go to Project Settings → Environment Variables
  2. Add new variable:
    • Name: DATABASE_URL
    • Value: Your connection string
    • Environments: Select all (Production, Preview, Development)
  3. Click “Save”

Prisma Schema

Your database schema is defined in prisma/schema.prisma:
model Subscription {
  id               String    @id @default(auto()) @map("_id") @db.ObjectId
  telegramUserId   String    // Telegram user ID
  telegramUsername String?
  telegramName     String?
  paystackRef      String    // Payment reference (unique per subscription)
  customerEmail    String?
  amountKobo       Int       // Payment amount in kobo
  planType         String    // "basic", "biweekly", "monthly", "premium"
  hasCopierAccess  Boolean   @default(false)  // Premium users get copier access
  startedAt        DateTime  @default(now())
  expiresAt        DateTime  // Calculated based on plan duration
  isRemoved        Boolean   @default(false)  // Marked true when user removed
  removedAt        DateTime?
  inviteLinkUsed   String?
  createdAt        DateTime  @default(now())
  updatedAt        DateTime  @updatedAt

  @@index([telegramUserId])
  @@index([expiresAt, isRemoved])
  @@index([planType])
}
The schema also includes Mt5Setup and ConversationState models for premium features like MT5 copier integration.

Initialize Database

1

Install Dependencies

Ensure Prisma is installed:
npm install
This installs:
  • @prisma/client - Prisma Client for database queries
  • prisma - Prisma CLI for migrations and management
2

Generate Prisma Client

Generate the TypeScript types and client:
npx prisma generate
This creates the Prisma Client based on your schema in prisma/schema.prisma.
Run this command whenever you modify the Prisma schema.
3

Push Schema to Database

For MongoDB, use db push to sync your schema:
npx prisma db push
This will:
  • Connect to your MongoDB Atlas cluster
  • Create the database if it doesn’t exist
  • Create collections for each model
  • Create indexes defined in the schema
Expected output:
Environment variables loaded from .env.local
Prisma schema loaded from prisma/schema.prisma
Datasource "db": MongoDB database

🚀  Your database is now in sync with your Prisma schema.

✔ Generated Prisma Client
If you see this output, your database is ready!
4

Verify Database (Optional)

Open Prisma Studio to visually inspect your database:
npx prisma studio
This opens a browser interface at http://localhost:5555 where you can:
  • View all collections
  • Browse records
  • Add/edit/delete data manually
  • Test queries
Prisma Studio is great for debugging and manually managing data during development.

Database Indexes

The schema includes optimized indexes for common queries:
ModelIndexPurpose
SubscriptiontelegramUserIdFast user lookup
SubscriptionexpiresAt, isRemovedEfficient cron job queries
SubscriptionplanTypeFilter by subscription plan
PromoCodeisActiveQuery active promo codes
PromoCodeexpiresAtFind expired promo codes
UsertelegramUserIdFast user authentication
MongoDB automatically creates these indexes when you run prisma db push.

Testing Database Connection

Create a simple test to verify your connection:
import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

async function main() {
  // Test connection
  const userCount = await prisma.user.count()
  console.log('✅ Database connected! User count:', userCount)

  // Create test user
  const testUser = await prisma.user.create({
    data: {
      telegramUserId: '123456789',
      telegramUsername: 'testuser',
      telegramName: 'Test User'
    }
  })
  console.log('✅ Test user created:', testUser)

  // Clean up
  await prisma.user.delete({
    where: { id: testUser.id }
  })
  console.log('✅ Test user deleted')
}

main()
  .catch(console.error)
  .finally(() => prisma.$disconnect())
Expected output:
✅ Database connected! User count: 0
✅ Test user created: { id: '...', telegramUserId: '123456789', ... }
✅ Test user deleted

Common Prisma Operations

Create Subscription

const subscription = await prisma.subscription.create({
  data: {
    telegramUserId: user.id.toString(),
    telegramUsername: user.username,
    telegramName: user.first_name,
    paystackRef: reference,
    amountKobo: 500000,
    planType: 'basic',
    expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000) // 7 days
  }
})

Find Active Subscription

const activeSubscription = await prisma.subscription.findFirst({
  where: {
    telegramUserId: userId,
    expiresAt: { gt: new Date() },
    isRemoved: false
  }
})

Find Expired Subscriptions

const expiredSubscriptions = await prisma.subscription.findMany({
  where: {
    expiresAt: { lt: new Date() },
    isRemoved: false
  }
})

Update Subscription

await prisma.subscription.update({
  where: { id: subscriptionId },
  data: {
    isRemoved: true,
    removedAt: new Date()
  }
})

Troubleshooting

Error: Error: Connection timeoutSolutions:
  1. Check Network Access:
    • Go to MongoDB Atlas → Network Access
    • Ensure 0.0.0.0/0 is added
    • Wait 2-3 minutes for changes to propagate
  2. Verify credentials:
    • Check username and password are correct
    • Ensure no special characters are unencoded
    • Test connection string in MongoDB Compass
  3. Check cluster status:
    • Go to Database → Clusters
    • Ensure cluster is not paused or provisioning
Error: Error: Authentication failedSolutions:
  1. Verify password:
    • Password is case-sensitive
    • Check for copy-paste errors
    • Ensure <password> placeholder is replaced
  2. Check user exists:
    • Go to Database Access
    • Verify user is created
    • Check user has “Read and write” privileges
  3. Special characters in password: If password has special characters, URL-encode them:
    • @%40
    • #%23
    • %%25
    • Or regenerate password without special characters
Error: Error: Database telegram_bot does not existSolution: MongoDB creates databases on first write. This is normal - just run:
npx prisma db push
The database will be created automatically.
Error during prisma generateSolutions:
  1. Clear Prisma cache:
    rm -rf node_modules/.prisma
    npx prisma generate
    
  2. Reinstall dependencies:
    npm install @prisma/client prisma
    npx prisma generate
    
  3. Check schema syntax: Ensure prisma/schema.prisma has no syntax errors.
Error: Error: DATABASE_URL environment variable not foundSolution: Prisma needs DATABASE_URL at build time:
  1. Go to Vercel → Project Settings → Environment Variables
  2. Add DATABASE_URL with your MongoDB connection string
  3. Ensure it’s enabled for all environments (Production, Preview, Development)
  4. Redeploy
The build command prisma generate requires DATABASE_URL to generate the client.

Database Maintenance

Backup Strategy

Free Tier (M0):
  • No automated backups
  • Export data manually via MongoDB Compass or mongodump
Paid Tiers (M10+):
  • Automated continuous backups
  • Point-in-time recovery
  • Scheduled snapshots

Export Data

Using Prisma Studio:
npx prisma studio
# Manually export from UI
Using MongoDB Compass:
  1. Download MongoDB Compass
  2. Connect with your connection string
  3. Export collections to JSON/CSV

Monitor Usage

Check database metrics in MongoDB Atlas:
  1. Go to Database → Metrics
  2. Monitor:
    • Connections
    • Operations per second
    • Storage usage
    • Network traffic
Set up alerts in Atlas to notify you when approaching storage or connection limits.

Next Steps

With your database configured, you’re ready to deploy:

Deploy to Vercel

Complete the deployment process

Test Your Bot

Verify everything works end-to-end

Build docs developers (and LLMs) love