From 50e647c64914008d04db4371bba9284bc553ca3b Mon Sep 17 00:00:00 2001 From: Vladyslav Halatskyi Date: Tue, 21 Jan 2025 15:43:58 +0200 Subject: [PATCH] fix: Insert a value on first increment call (#187) --- src/main/server/document/global.ts | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/src/main/server/document/global.ts b/src/main/server/document/global.ts index 00f939506..9d28a47f8 100644 --- a/src/main/server/document/global.ts +++ b/src/main/server/document/global.ts @@ -81,14 +81,17 @@ export async function useGlobal(identifier: string) { */ async function increment(fieldName: string, value: number = 1): Promise { const client = await db.getClient(); - const updatedValue = await client - .collection(CollectionNames.Global) - .findOneAndUpdate( - { _id: data[identifier]._id }, - { $inc: { [fieldName]: value } }, - { upsert: true, returnDocument: 'after' }, - ); - data[identifier][fieldName] = updatedValue.value[fieldName]; + if (data[identifier][fieldName] !== undefined) { + const updatedValue = await client + .collection(CollectionNames.Global) + .findOneAndUpdate({ identifier }, { $inc: { [fieldName]: value } }, { returnDocument: 'after' }); + data[identifier][fieldName] = updatedValue[fieldName]; + } else { + const updatedValue = await client + .collection(CollectionNames.Global) + .findOneAndUpdate({ identifier }, { $set: { [fieldName]: value } }, { returnDocument: 'after' }); + data[identifier][fieldName] = updatedValue[fieldName]; + } return data[identifier][fieldName]; }