Skip to content

The Socket.IO MongoDB adapter, allowing to broadcast events between several Socket.IO servers

License

Notifications You must be signed in to change notification settings

veracity-tech/socket.io-mongo-adapter-singleton

 
 

Repository files navigation

Socket.IO MongoDB adapter

The @socket.io/mongo-adapter package allows broadcasting packets between multiple Socket.IO servers.

Adapter diagram

Unlike the existing socket.io-adapter-mongo package which uses tailable cursors, this package relies on change streams and thus requires a replica set or a sharded cluster.

Supported features:

Related packages:

Table of contents

Installation

npm install @socket.io/mongo-adapter mongodb

For TypeScript users, you might also need @types/mongodb.

Usage

const { Server } = require("socket.io");
const { createAdapter } = require("@socket.io/mongo-adapter");
const { MongoClient } = require("mongodb");

const DB = "mydb";
const COLLECTION = "socket.io-adapter-events";

const io = new Server();

const mongoClient = new MongoClient("mongodb://localhost:27017/?replicaSet=rs0", {
  useUnifiedTopology: true,
});

const main = async () => {
  await mongoClient.connect();

  try {
    await mongoClient.db(DB).createCollection(COLLECTION, {
      capped: true,
      size: 1e6
    });
  } catch (e) {
    // collection already exists
  }
  const mongoCollection = mongoClient.db(DB).collection(COLLECTION);

  io.adapter(createAdapter(mongoCollection));
  io.listen(3000);
}

main();

Note: the capped collection prevents the collection from growing too big.

Known errors

  • MongoError: The $changeStream stage is only supported on replica sets

Change streams are only available for replica sets and sharded clusters.

More information here.

Please note that, for development purposes, you can have a single MongoDB process acting as a replica set by running rs.initiate() on the node.

  • TypeError: this.mongoCollection.insertOne is not a function

You probably passed a MongoDB client instead of a MongoDB collection to the createAdapter method.

License

MIT

About

The Socket.IO MongoDB adapter, allowing to broadcast events between several Socket.IO servers

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • TypeScript 100.0%