ShareDB MongoDB Adapter
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
-
Query hangs when using $map operator.
cause A bug in the `$map` query transform implementation.fixUpgrade to `sharedb-mongo@4.1.1` or later, which includes a fix for this issue. Avoid using `$map` in earlier versions. -
Memory leak detected when performing cursor operations like `$count`.
cause A memory leak issue affecting `mongodb@4-6` when using cursor operations such as `$count` or `$explain`.fixUpgrade to `sharedb-mongo@4.1.1` or later, which resolved this memory leak. -
TypeError: ShareDbMongo is not a constructor
cause Attempting to use `require('sharedb-mongo')` directly as a class constructor in CommonJS, or incorrect ESM import.fixIf using CommonJS, `require('sharedb-mongo')` returns a function; call it with `const db = require('sharedb-mongo')(url);`. If using ESM, ensure `import ShareDbMongo from 'sharedb-mongo';` and then `new ShareDbMongo(url);`.
Warnings
- breaking Node.js v16 support was dropped with the release of v5.0.0. Projects using Node.js v16 or earlier must upgrade their Node.js environment to a supported version (Node.js v18 or later is recommended).
- breaking Node.js v14 support was dropped with the release of v4.0.0. Users on Node.js v14 need to upgrade their runtime.
- breaking Support for `mongodb@2` was dropped in v3.0.0. Users connecting to older MongoDB server versions or using older `mongodb` driver versions must upgrade their MongoDB setup.
- gotcha Direct modification of ShareDB documents using the native MongoDB driver or command line is strictly prohibited. This can lead to data inconsistencies and corruption as ShareDB's operational transformation mechanism will be bypassed.
- gotcha The default `src`/`seq`/`v` index is created automatically. If you're using `sharedb@5.0.1` or later which aims to avoid this index, you can disable its creation via `disableIndexCreation` option in `sharedb-mongo` v4.2.0+. Existing, undesired indexes must be manually deleted from MongoDB.
Install
-
npm install sharedb-mongo -
yarn add sharedb-mongo -
pnpm add sharedb-mongo
Imports
- ShareDbMongo
const ShareDbMongo = require('sharedb-mongo');import ShareDbMongo from 'sharedb-mongo';
- ShareDbMongo
const db = require('sharedb-mongo')('mongodb://localhost:27017/test'); - { mongoOptions: {...} } (configuration)
new ShareDbMongo('mongodb://localhost:27017/test', { /* top-level mongo options */ });import ShareDbMongo from 'sharedb-mongo'; new ShareDbMongo('mongodb://localhost:27017/test', { mongoOptions: { /* ... */ } });
Quickstart
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!');
});
}
});