olexnzarov / telegraf-session-mongodb

MongoDB session middleware for Telegraf
25 stars 14 forks source link

How to retrieve a specific object? #6

Closed expelliamus closed 4 years ago

expelliamus commented 4 years ago

Hi,

I'm using your library for a persistent session and is working really well. Anyway, I would ask a question, I need to get a specific object in the sessions document eh: __language_code (i18n Middleware object). At the moment I did:

const { TelegrafMongoSession } = require('telegraf-session-mongodb');
const Telegraf = require('telegraf');
const bot = new Telegraf(process.env.TOKEN);

TelegrafMongoSession.setup(bot, process.ENV.MONGODB_URI)

.then((client) => bot.launch()) .catch((err) => console.log(Failed to connect to the database: ${err}));

Is there a way to access to the session stored objects/values using the session instance? How?

Kind regards

olexnzarov commented 4 years ago

Hey.

TelegrafMongoSession.setup returns a Promise that resolves to the MongoClient object. You can use this object to find anything you want in the connected database, like this:


TelegrafMongoSession.setup(bot, process.ENV.MONGODB_URI)
  .then(client => {
    const db = client.db();
    const sessions = db.collection('sessions');

    // do whatever you need with the sessions collection
  });
olexnzarov commented 4 years ago

It would be something like this:

  const { data: { __language_code } } = await sessions.findOne({ key: `${userId}:${userId}` });

But if you have a context it's much easier:

  const { session: { __language_code } } = ctx;