How to copy a new yDoc into mongodb and send to client?

I have recently used yjs, so my question may seem silly, but I have been looking for a long time and have not found the right way

I am using GitHub - MaxNoetzold/y-mongodb-provider: Mongodb database adapter for Yjs for persistence storage. This is the code for persistence, taken from the README:

setPersistence({
      bindState: async (docName: string, ydoc: Y.Doc) => {
        // Here you listen to granular document updates and store them in the database
        // You don't have to do this, but it ensures that you don't lose content when the server crashes
        // See https://github.com/yjs/yjs#Document-Updates for documentation on how to encode
        // document updates

        // official default code from: https://github.com/yjs/y-websocket/blob/37887badc1f00326855a29fc6b9197745866c3aa/bin/utils.js#L36
        const persistedYdoc = await mdb.getYDoc(docName);
        const newUpdates = Y.encodeStateAsUpdate(ydoc);
        mdb.storeUpdate(docName, newUpdates);
        Y.applyUpdate(ydoc, Y.encodeStateAsUpdate(persistedYdoc));
        ydoc.on('update', async (update) => {
          mdb.storeUpdate(docName, update);
        });
      },
      writeState: async (docName, ydoc) => {
        // This is called when all connections to the document are closed.
        // In the future, this method might also be called in intervals or after a certain number of updates.
        return new Promise((resolve) => {
          // When the returned Promise resolves, the document will be destroyed.
          // So make sure that the document really has been written to the database.
          resolve(undefined);
        });
      },
    });

Now, I have implemented an interface for replicating documents. Here is the code:

async duplicate(sourceFileId: string, destFileId: string): Promise<void> {
        const mdb = this.getMongodbPersistence();
        let sourceDocName = this.generateDocNameByFileId(sourceFileId);
        let destDocName = this.generateDocNameByFileId(destFileId);

        const sourceYdoc = await mdb.getYDoc(sourceDocName);

        mdb.storeUpdate(destDocName, Y.encodeStateAsUpdate(sourceYdoc));

        const destYdoc = await mdb.getYDoc(destDocName);
    }

From my observation, it seems that the content of destYdoc has been replicated. However, when I send the doc to the client through setPersistence, the content is incomplete.

@raine Hello, I see that you are quite active. Do you have time to help me with a question? Should I provide any additional information? Thank you!

On first glance, it seems that you need to await the mdb.storeUpdate call.

Admittedly it is true, I am quite active here. However, that does not give you the prerogative to call me out specifically. Iā€™m not YJS customer service :wink:

1 Like