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.
This commit is contained in:
parent
35deda5963
commit
c6214a34ff
1 changed files with 19 additions and 12 deletions
|
|
@ -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
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue