Document from y-leveldb doesn't seem to be fully hydrated?

I have the following to experiment with y-leveldb, adapted slightly from the README:

import {LeveldbPersistence} from 'y-leveldb'
import * as Y from 'yjs';

(async function main() {
  const persistence = new LeveldbPersistence('./storage-location')

  const ydoc = new Y.Doc()
  ydoc.getArray('arr').insert(0, [1, 2, 3])
  ydoc.getArray('arr').toArray() // => [1, 2, 3]

  // store document updates retrieved from other clients
  persistence.storeUpdate('my-doc', Y.encodeStateAsUpdate(ydoc));

  // when you want to sync, or store data to a database,
  // retrieve the temporary Y.Doc to consume data
  console.log((await persistence.getYDoc('my-doc')).getArray('arr').toArray()) // [1, 2, 3]
  console.log((await persistence.getYDoc('my-doc')).toJSON()) // ???
})();

The first console.log gets the document, indexes into it to get a shared type, and prints it. This works fine, I see [ 1, 2, 3 ].

The second console.log gets the document, converts it to a JS object via toJSON and prints it. However, this prints just the keys of the document, without the value: { arr: undefined }.

I’m sure there’s something incredibly stupid I’m doing, forgive me. Thank you for your hard work on this family of projects!

I’ve bumped in to this before as well. Once data is persisted, it loses type information (no schema is stored), so it must be reconstructed using your app’s knowledge of what the types are.

In other words, when you say persistence.getYDoc('my-doc')).getArray('arr') you are not only getting the array, you are also informing the document that the type of arr on my-doc is an array. In the persistence.getYDoc('my-doc')).toJSON() case, my-doc knows it has an arr “something” but doesn’t know that it is an array.

1 Like