{"id":16589,"library":"y-mongodb-provider","title":"MongoDB Persistence Provider for Yjs","description":"y-mongodb-provider is a database adapter that enables persistent storage and retrieval of Yjs collaborative documents using MongoDB. It serves as a backend for y-websocket servers, allowing Yjs document states to be saved and loaded, thereby ensuring data durability across server restarts or disconnections. The current stable version is 0.2.1, with updates primarily focused on dependency management, internal driver improvements, and bug fixes, indicating an active development status though without a strict release cadence. Key differentiators include its specific integration with MongoDB (unlike Yjs's officially supported y-leveldb), its ability to handle Yjs updates exceeding MongoDB's 16MB document size limit (since v0.1.8), and its use of the official MongoDB Node.js Driver for enhanced security and performance. It's important to note that this package is not officially supported by the Yjs team.","status":"active","version":"0.2.1","language":"javascript","source_language":"en","source_url":"https://github.com/MaxNoetzold/y-mongodb-provider","tags":["javascript","Yjs","MongoDB","database","adapter","shared editing","collaboration","offline","CRDT","typescript"],"install":[{"cmd":"npm install y-mongodb-provider","lang":"bash","label":"npm"},{"cmd":"yarn add y-mongodb-provider","lang":"bash","label":"yarn"},{"cmd":"pnpm add y-mongodb-provider","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Core Yjs library, required for Yjs document structure and operations.","package":"yjs","optional":false}],"imports":[{"note":"This package is primarily ESM-first, requiring Node.js 16+. Named import is the standard way. Ships TypeScript types.","wrong":"const { MongodbPersistence } = require('y-mongodb-provider')","symbol":"MongodbPersistence","correct":"import { MongodbPersistence } from 'y-mongodb-provider'"},{"note":"The constructor accepts a MongoDB connection string. Since v0.2.0+, ensure proper database name in the string for authentication purposes.","symbol":"MongodbPersistence constructor (connection string)","correct":"new MongodbPersistence('mongodb://localhost:27017/yjstest')"},{"note":"Passing an object with `MongoClient` and `Db` instances is recommended for managing connection pools and resource sharing, especially when the same client is used elsewhere in your application.","symbol":"MongodbPersistence constructor (client object)","correct":"import { MongoClient } from 'mongodb'; const client = new MongoClient('mongodb://localhost:27017'); await client.connect(); const db = client.db('yourDatabaseName'); new MongodbPersistence({ client, db })"}],"quickstart":{"code":"import http from 'http';\nimport { WebSocketServer } from 'ws';\nimport * as Y from 'yjs';\nimport { MongodbPersistence } from 'y-mongodb-provider';\nimport yUtils from 'y-websocket/bin/utils'; // Note: y-websocket/bin/utils is an internal utility, adapt as needed.\n\nconst port = process.env.PORT || 1234;\nconst mongoConnectionString = process.env.MONGODB_URL || 'mongodb://localhost:27017/yjstest';\n\nconst server = http.createServer((request, response) => {\n\tresponse.writeHead(200, { 'Content-Type': 'text/plain' });\n\tresponse.end('okay');\n});\n\n// Initialize Yjs WebSocket server\nconst wss = new WebSocketServer({ server });\nwss.on('connection', yUtils.setupWSConnection);\n\n// Initialize MongoDB persistence for Yjs\nconst mdb = new MongodbPersistence(mongoConnectionString, {\n\tcollectionName: 'transactions',\n\tflushSize: 100,\n\tmultipleCollections: false, // Default; set to true if each document needs its own collection\n});\n\n// Set up persistence with y-websocket\nyUtils.setPersistence({\n\tbindState: async (docName, ydoc) => {\n\t\t// Retrieve the persisted document state\n\t\tconst persistedYdoc = await mdb.getYDoc(docName);\n\t\t\n\t\t// Apply the persisted state to the current ydoc\n\t\tY.applyUpdate(ydoc, Y.encodeStateAsUpdate(persistedYdoc));\n\n\t\t// Store initial state and listen for future updates\n\t\tmdb.storeUpdate(docName, Y.encodeStateAsUpdate(ydoc));\n\t\tydoc.on('update', async (update) => {\n\t\t\tmdb.storeUpdate(docName, update);\n\t\t});\n\t},\n\twriteState: async (docName, ydoc) => {\n\t\t// This function is called when all connections to a document are closed.\n\t\t// Ensure all pending updates are written to the database.\n\t\t// For y-mongodb-provider, `storeUpdate` handles this incrementally.\n\t\t// The promise resolution signals that the document can be destroyed.\n\t\treturn new Promise(resolve => resolve());\n\t},\n});\n\nserver.listen(port, () => {\n\tconsole.log(`Yjs WebSocket server with MongoDB persistence listening on port: ${port}`);\n});\n","lang":"javascript","description":"This example sets up a Yjs WebSocket server using `y-websocket` and integrates `y-mongodb-provider` for persistent storage of Yjs document states in a MongoDB database. It demonstrates binding document state on connection and asynchronously storing updates as they occur."},"warnings":[{"fix":"Review the GitHub repository for active development, open issues, and pull requests to gauge maintenance status and potential issues. Consider contributing to its development if you find gaps.","message":"This `y-mongodb-provider` package is not officially supported or maintained by the core Yjs team. While functional, users should be aware of its community-driven support model.","severity":"gotcha","affected_versions":">=0.1.6"},{"fix":"Upgrade your Node.js environment to version 16 or later (e.g., `nvm install 16 && nvm use 16`).","message":"Node.js version 16 or newer is required to use this package. Using older Node.js versions will result in runtime errors due to reliance on modern JavaScript features and ESM module format.","severity":"breaking","affected_versions":">=0.1.6"},{"fix":"Review the official MongoDB Node.js driver documentation for any specific connection string options or client configurations, especially if encountering unexpected behavior when migrating from versions prior to 0.1.8.","message":"Version 0.1.8 replaced the internal 'mongoist' library with the official 'mongodb' Node.js Driver. While the public API signature for `MongodbPersistence` generally remained, internal behaviors, error handling, or specific connection options might have changed. This change was also made for security enhancements.","severity":"breaking","affected_versions":">=0.1.8"},{"fix":"Manually instantiate `MongoClient`, connect it, and pass the `{ client, db: client.db('yourDatabaseName') }` object to the `MongodbPersistence` constructor.","message":"For optimal performance and robust connection pooling, especially when sharing a `MongoClient` instance across your application, it is recommended to pass an object `{ client: MongoClient, db: Db }` to the `MongodbPersistence` constructor instead of just a connection string. This avoids creating redundant MongoDB client instances.","severity":"gotcha","affected_versions":">=0.1.6"},{"fix":"Ensure that if you intend to store all documents within a single, named collection, `multipleCollections` must be set to `false` (which is its default value).","message":"If the `multipleCollections` option is set to `true` in the `MongodbPersistence` constructor, each Yjs document will be stored in its own dedicated MongoDB collection. In this scenario, the `collectionName` option will be ignored.","severity":"gotcha","affected_versions":">=0.1.6"},{"fix":"Verify that the database name specified in your MongoDB connection string or through the `client.db('databaseName')` call accurately corresponds to the database against which your MongoDB user is authenticated and has the necessary permissions.","message":"Version 0.2.0 introduced changes to the `MongodbPersistence` constructor's internal handling of the database name for user authentication. While passing a connection string is still supported, improper database naming could lead to authentication failures or incorrect access rights.","severity":"breaking","affected_versions":">=0.2.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[],"ecosystem":"npm"}