ShareDB MongoDB Adapter

5.1.0 · active · verified Wed Apr 22

sharedb-mongo is a database adapter for ShareDB, a full-stack library for realtime JSON document collaboration. It serves as both a snapshot store and an oplog for ShareDB documents, integrating directly with MongoDB. Currently at v5.1.0, the package sees active development with regular updates to support the latest Node.js and MongoDB versions. A key differentiator is its ability to unwrap JSON document snapshots, allowing direct MongoDB queries against these documents (for read-only operations), while strictly requiring ShareDB for any modifications to ensure proper operational transformation and persistence. It also extends MongoDB's querying capabilities within the ShareDB context through special `$`-prefixed operators for methods like `mapReduce` and `sort`.

Common errors

Warnings

Install

Imports

Quickstart

Initializes a ShareDB backend with sharedb-mongo as the database adapter and sets up a basic WebSocket server for client connections.

import ShareDB from 'sharedb';
import ShareDbMongo from 'sharedb-mongo';
import { WebSocketServer } from 'ws';
import http from 'http';

const mongoUrl = 'mongodb://localhost:27017/test';
const db = new ShareDbMongo(mongoUrl);
const backend = new ShareDB({ db });

// Create a WebSocket server to listen for client connections
const server = http.createServer();
const wss = new WebSocketServer({ server });

wss.on('connection', (ws) => {
  // Connect client to ShareDB backend
  const stream = backend.connect(ws);
  // Handle stream errors
  stream.on('error', (err) => console.error('ShareDB stream error:', err));
});

server.listen(8080, () => {
  console.log('ShareDB server listening on http://localhost:8080');
  console.log(`Connected to MongoDB at ${mongoUrl}`);
});

// Example document creation (optional, for testing)
const connection = backend.connect();
const doc = connection.get('examples', 'myDocument');
doc.fetch((err) => {
  if (err) throw err;
  if (doc.type === null) {
    doc.create({ content: 'Hello, ShareDB!' }, 'json0', (err) => {
      if (err) console.error('Error creating document:', err);
      else console.log('Document created!');
    });
  }
});

view raw JSON →