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,12 +5,15 @@ export default defineEventHandler(async (event) => {
|
||||||
const transactions = await readBody(event)
|
const transactions = await readBody(event)
|
||||||
const collection = await getCollection('transactions')
|
const collection = await getCollection('transactions')
|
||||||
|
|
||||||
// Clear existing transactions and insert new ones
|
// Clear existing transactions and upsert new ones
|
||||||
await collection.deleteMany({})
|
await collection.deleteMany({})
|
||||||
|
|
||||||
if (transactions.length > 0) {
|
if (transactions.length > 0) {
|
||||||
// Convert transactions for MongoDB
|
// Convert transactions for MongoDB and use bulk upsert operations
|
||||||
const mongoTransactions = transactions.map(transaction => ({
|
const bulkOps = transactions.map(transaction => ({
|
||||||
|
replaceOne: {
|
||||||
|
filter: { _id: transaction.id },
|
||||||
|
replacement: {
|
||||||
...transaction,
|
...transaction,
|
||||||
_id: transaction.id,
|
_id: transaction.id,
|
||||||
id: undefined,
|
id: undefined,
|
||||||
|
|
@ -18,13 +21,17 @@ export default defineEventHandler(async (event) => {
|
||||||
endDate: transaction.endDate ? new Date(transaction.endDate) : null,
|
endDate: transaction.endDate ? new Date(transaction.endDate) : null,
|
||||||
createdAt: new Date(),
|
createdAt: new Date(),
|
||||||
updatedAt: new Date()
|
updatedAt: new Date()
|
||||||
|
},
|
||||||
|
upsert: true
|
||||||
|
}
|
||||||
}))
|
}))
|
||||||
|
|
||||||
const result = await collection.insertMany(mongoTransactions)
|
const result = await collection.bulkWrite(bulkOps)
|
||||||
|
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
insertedCount: result.insertedCount
|
insertedCount: result.upsertedCount,
|
||||||
|
modifiedCount: result.modifiedCount
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue