I had to solve this problem and I looked for advice from this thread. Might as well update my approach.
So when I fetch the document from the DB, if it doesn’t exist I create a new y.Doc and then immediately run doc.createDefaultDoc()
which is just:
createDefaultDoc() {
const node = schema.nodes.doc.createAndFill()
applyUpdate(this.yDoc, encodeStateAsUpdate(prosemirrorToYDoc(node, 'pm-doc')))
}
Then I immediately write that update to DB. Think that’s the simplest and safest approach. If you allow creation of new documents from client-side, then it becomes a problem to see who has initialized the doc. I’d advise not to do that. Or at least make sure no one else can create the same doc with the same id.