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