How to decode the document data from the persisted data

I am trying to save the IDE data in mongoDB. What I am planning to do is after a room ends get the code from mongoDB collection for which I used y-mongodb and then save that data in another collection and delete the current document.

const persistedYdoc = await ldb.getYDoc(docName);
const newUpdates = Y.encodeStateAsUpdate(persistedYdoc);

My newUpdates are logged as:

Uint8Array(188) [
    5,   1, 172, 227, 196, 139,  15,   0, 132, 188, 169, 142,
  176,  12,  37,   8,  10,  10, 100, 119, 101, 100, 119, 101,
    1, 206, 185, 147, 175,  14,   0, 132, 195, 149, 249, 240,
    8,  28,   9,  10, 100,  10, 119, 101, 100, 119, 101, 100,
    1, 188, 169, 142, 176,  12,   0, 132, 206, 185, 147, 175,
   14,   8,  38,  10, 100, 115, 102,  97, 115, 100, 102, 115,
  100, 102,  10, 115, 100,  10, 102, 115, 100, 102, 100, 102,
  115,  10, 100, 102,  10,  97, 115, 100,  10, 102,  97, 115,
  100, 102, 115, 100,

Document stored in mongoDb as
image

I need help decoding the value from the given format.

This is all documented here: Document Updates - Yjs Docs

I decoded using the package but it seems it is not reading some characters properly. But on the editor its showing the exact thing I typed.
After decoding and logging the data
image

Fetching directly from yjs

My name is Naman Aggarwal. Whats your Name?

Code I used for decoding

const persistedYdoc = await ldb.getYDoc(docName);
  const newUpdates = Y.encodeStateAsUpdate(persistedYdoc);
  const temp = fromUint8Array(newUpdates);
  console.log(temp);
  const resp = Base64.atob(temp);

Hi Naman, This is not how you can use document updates. You can encode state, and you can apply encoded state to another Yjs document. However, you are not supposed to read document updates because they encode CRDT operations that are probably of no help to you. You should not attempt to read CRDT operations because you need Yjs or Y-CRDT to decode and apply them.

Everything you can do with document updates is documented here: https://docs.yjs.dev/api/document-updates

Everything else is basically unsupported.

1 Like