From c6214a34ffbf5afd34705d3586c6ad6e7ef68be8 Mon Sep 17 00:00:00 2001 From: Jennie Robinson Faber Date: Sat, 23 Aug 2025 15:05:01 +0100 Subject: [PATCH] Refactor bulk transaction handling in bulk.put.js to use bulk upsert operations - Updated the transaction processing logic to clear existing transactions and perform bulk upserts instead of inserts. - Enhanced the response to include counts of upserted and modified transactions. --- server/api/transactions/bulk.put.js | 31 ++++++++++++++++++----------- 1 file changed, 19 insertions(+), 12 deletions(-) diff --git a/server/api/transactions/bulk.put.js b/server/api/transactions/bulk.put.js index 7d6d4a3..8b18f6d 100644 --- a/server/api/transactions/bulk.put.js +++ b/server/api/transactions/bulk.put.js @@ -5,26 +5,33 @@ export default defineEventHandler(async (event) => { const transactions = await readBody(event) const collection = await getCollection('transactions') - // Clear existing transactions and insert new ones + // Clear existing transactions and upsert new ones await collection.deleteMany({}) if (transactions.length > 0) { - // Convert transactions for MongoDB - const mongoTransactions = transactions.map(transaction => ({ - ...transaction, - _id: transaction.id, - id: undefined, - date: new Date(transaction.date), - endDate: transaction.endDate ? new Date(transaction.endDate) : null, - createdAt: new Date(), - updatedAt: new Date() + // Convert transactions for MongoDB and use bulk upsert operations + const bulkOps = transactions.map(transaction => ({ + replaceOne: { + filter: { _id: transaction.id }, + replacement: { + ...transaction, + _id: transaction.id, + id: undefined, + date: new Date(transaction.date), + endDate: transaction.endDate ? new Date(transaction.endDate) : null, + createdAt: new Date(), + updatedAt: new Date() + }, + upsert: true + } })) - const result = await collection.insertMany(mongoTransactions) + const result = await collection.bulkWrite(bulkOps) return { success: true, - insertedCount: result.insertedCount + insertedCount: result.upsertedCount, + modifiedCount: result.modifiedCount } }