Save and update document to mongodb

Hey i want to confiugre how to Save and update document in database using mongoDb, this code that i have in my server side:

const hocusServer = Server.configure({
    name: 'server',
    extensions: [
        new Logger(),
    ],
    yDocOptions: {
        gc: false,
        gcFilter: () => false, // Disable garbage collection
    },
    async onConnect(data) {
        ...
    },

    async onChange(data) {
       ...
    },

    async onStoreDocument(data) {
        await storeDocument(data);
        await storeSnapshots(data);
        console.log(`${colors.yellow(getTimestamp())} Document stored in "${data.documentName}"`);
    },

    async onDisconnect(data) {
        console.log('====================================');
        console.log(` ${(`Total connect in ${colors.bgBlue(data.documentName)}: ${data.clientsCount}`)}`);
        console.log('====================================');
    },
});

i handle saving and my update document in onStoreDocument(data), this is the code for stroreDocument function to handle inserting or updating data to database:

export async function storeDocument(data: any) {
    const db = await getDBInstance();
    const name = data.document.name;
    const json = transformer.fromYdoc(data.document, rootFragmentField);
    console.log(json.content);
    const content = JSON.stringify(json.content, null, 2);

    try {
        const existingDocument = await db.collection('document').findOne({ name });
        if (existingDocument) {
            await db.collection('document').updateOne(
                { _id: existingDocument._id },
                { $set: { content, "updatedAt": getTimestamp() } }
            );
            console.log(`[ ${colors.yellow(getTimestamp())} ] Updated document with name: ${name}`);
        } else {
            await db.collection('document').insertOne({ name, content, "createdAt": getTimestamp(), "updatedAt": getTimestamp() });
            console.log(`[ ${colors.yellow(getTimestamp())} ] Inserted new document with name: ${name}`);
        }
    } catch (error) {
        console.log(`[ ${colors.yellow(getTimestamp())} ] Error upserting document: ${error}`);
    }
}

this is are my current approach to save and update document at database, Are there any better approach? Thank you

I recommend y-mongodb-provider:

I’m using the following bindState method to load a document and store new updates:

// setup db persistence instance
const db = new MongodbPersistence(connectionString)

/** Syncs a doc with mongodb and subscribes to updates (throttled). */
const bindState = async ({docName, doc}: {
  docName: string
  doc: Y.Doc
}): Promise<void> => {
  const docPersisted = await db.getYDoc(docName)

  // sync doc state to db
  const update = Y.encodeStateAsUpdate(doc)
  if (update.length > 2) {
    await db.storeUpdate(docName, update)
  }

  // sync db state to doc
  Y.applyUpdate(doc, Y.encodeStateAsUpdate(docPersisted))

  // store update without throttling (seems bad)
  // const storeUpdate = (update: Uint8Array) => 
  //  db.storeUpdate(docName, update)

  // throttled update handler stores updates every 1000 ms
  const storeUpdate = throttleConcat(
    (updates: Uint8Array[]) =>
      updates.length > 0
        ? db.storeUpdate(docName, Y.mergeUpdates(updates))
        : null,
    1000,
  )

  doc.on('update', storeUpdate)
}