multi-mongo
v1.1.5
Published
MongoDB-based auth store for Baileys with single-collection multi-session in one collection support.
Maintainers
Readme
multi-mongo
A lightweight and efficient MongoDB-based store for Baileys that allows you to connect and manage multiple WhatsApp sessions in a single collection.
This package is inspired by mongo-baileys but optimized for multi-session management.
Features
✅ Store multiple WhatsApp sessions in one MongoDB collection
✅ Fully compatible with Baileys v7+
✅ Session-based auth state for easy scaling
✅ Simple integration with any Node.js backend
✅ TypeScript support out of the box
Installation
npm install multi-mongo
import { MongoClient } from 'mongodb';
import { makeWASocket, AnyMessageContent } from '@whiskeysockets/baileys';
import { useMongoDBAuthState } from 'multi-mongo';
import Boom from '@hapi/boom';
const url = "YOUR_MONGODB_URL";
const dbName = "whatsapp";
const collectionName = "authState";
async function connectToMongoDB() {
const client = new MongoClient(url);
await client.connect();
const db = client.db(dbName);
const collection = db.collection(collectionName);
return { client, collection };
}
async function startWhatsApp(deviceId) {
const { collection } = await connectToMongoDB();
const { state, saveCreds } = await useMongoDBAuthState(collection,deviceId);
const sock = makeWASocket({
auth: state,
printQRInTerminal: true,
});
sock.ev.on('creds.update', saveCreds);
sock.ev.on('connection.update', (update) => {
const { connection, lastDisconnect } = update;
if (connection === 'close') {
const shouldReconnect = lastDisconnect && lastDisconnect.error
? Boom.boomify(lastDisconnect.error).output.statusCode
: 500;
console.log('Connection closed due to', lastDisconnect?.error, ', reconnecting in', shouldReconnect, 'ms');
if (shouldReconnect) {
setTimeout(() => startWhatsApp(), shouldReconnect);
}
} else if (connection === 'open') {
console.log('Opened connection');
}
});
sock.ev.on('messages.upsert', async (m) => {
console.log(JSON.stringify(m, null, 2));
const message = m.messages[0];
if (message && !message.key.fromMe && m.type === 'notify') {
console.log('Replying to', message.key.remoteJid);
await sock.sendMessage(message.key.remoteJid, { text: 'Hello there!' });
}
});
// Graceful shutdown
process.on('SIGINT', async () => {
console.log('Received SIGINT. Closing connection...');
await sock.close();
process.exit();
});
process.on('SIGTERM', async () => {
console.log('Received SIGTERM. Closing connection...');
await sock.close();
process.exit();
});
}
startWhatsApp(deviceId).catch(err => console.error("Unexpected error:", err));