MongoDB error connect to DB (Bot telegram) session instalation

Hello,
I want to ask, I’m getting an error while running mongodb for telegram bot. the error is Error connecting to MongoDB: TypeError: session is not a constructor. Here I show the code file database.js

const connectToDatabase = async () => {
  try {
    const uri = process.env.MONGODB_URI;
    const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
    await client.connect();
    console.log('Connected to MongoDB successfully');
    const db = client.db();
    const sessions = new session(db, {
      collectionName: 'session',
      sessionName: 'telegrafSessions'
    });
    return { db, sessions };
  } catch (error) {
    console.error('Error connecting to MongoDB:', error);
    throw error;
  }
};

The modules that I installed on database.js

const { MongoClient } = require('mongodb');
const { session } = require('telegraf-session-mongodb');

Here is the index.js file for connecting to the database.js file

const { Telegraf, Markup } = require('telegraf');
const { connectToDatabase, saveUserSession, saveUserLog } = require('./src/database');
// Connect database
connectToDatabase()
.then(({ db, sessions }) => {
    // Middleware session user
    bot.use(sessions.middleware());

    bot.use(async (ctx, next) => {
      ctx.session.db = db; // insert object db session
      await next();
    });

    // Middleware save user telegram
    bot.use((ctx, next) => {
      saveUserSession(db, ctx.session)
        .then(() => next())
        .catch((error) => {
          console.error('Error saving user session:', error);
          ctx.reply('Oops! Something went wrong.');
        });
    });
    // Middleware save log user telegram
    bot.use((ctx, next) => {
      const log = {
        session_id: ctx.session.session_id,
        user_id: ctx.from.id,
        timestamp: new Date(),
        message: ctx.message.text
      };
      saveUserLog(db, log);
      return next();
    });

Hi @Ekacitta_Wibisono,

Welcome to the MongoDB Community!

Based on the shared details, the error doesn’t seems to be related to MongoDB rather it is occurring from the above code snippet because the session is not a constructor so adding a new keyword in-front of it make it throw an error.

So, to avoid this error message first connect to the MongoDB database and then use the connectToDatabase() function to further start a bot. Sharing the code snippet for your reference:

// Connect to the database and return the database object
const connectToDatabase = async () => {
    try {
        const uri = process.env.MONGODB_URI || "mongodb://localhost:27017"; // Use the environment variable if available, otherwise use the local URL
        const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
        await client.connect();

        console.log('Connected to MongoDB successfully');

        return client.db(); 
    } catch (error) {
        console.error('Error connecting to MongoDB:', error);
        throw error;
    }
};

// Connect database and start the bot
connectToDatabase()
    .then((db) => {
        const bot = new Telegraf('YOUR_TELEGRAM_BOT_TOKEN'); // Replace 'YOUR_TELEGRAM_BOT_TOKEN' with your actual bot token

        // Middleware to manage user sessions
        bot.use(session(db, { sessionName: 'test', collectionName: 'sessions' })); // Replace 'test' with your actual database name

        bot.use(async (ctx, next) => {
            ctx.db = db; 
            await next();
        });
...

I’ve only briefly tested this out so I recommend evaluating the code in your test environment to see if it suits your use case and requirements.

To learn more, please refer to telegraf-session-mongodb - npm documentation.

Hope the above helps!

Regards,
Kushagra