* Executes the MongoDB bulk write operation. * @param db The MongoDB database instance. * @param collectionName The name of the collection to update. * @param operations The array of bulk write operations.
( db: Db, collectionName: string, operations: AnyBulkWriteOperation<Document>[] )
| 118 | * @param operations The array of bulk write operations. |
| 119 | */ |
| 120 | async function executeBulkWrite( |
| 121 | db: Db, |
| 122 | collectionName: string, |
| 123 | operations: AnyBulkWriteOperation<Document>[] |
| 124 | ): Promise<void> { |
| 125 | if (operations.length === 0) { |
| 126 | console.log(`No changes detected for collection '${collectionName}'.`); |
| 127 | return; |
| 128 | } |
| 129 | |
| 130 | const upsertCount = operations.filter((op) => MONGO_OP_UPDATE_ONE in op).length; |
| 131 | const deleteCount = operations.filter((op) => MONGO_OP_DELETE_ONE in op).length; |
| 132 | console.log( |
| 133 | `Attempting ${upsertCount} upserts and ${deleteCount} deletions in collection '${collectionName}'...` |
| 134 | ); |
| 135 | |
| 136 | try { |
| 137 | const collection = db.collection(collectionName); |
| 138 | const bulkWriteResult = await collection.bulkWrite(operations, { ordered: false }); |
| 139 | console.log( |
| 140 | `Bulk write completed: ${bulkWriteResult.upsertedCount} upserted, ` + |
| 141 | `${bulkWriteResult.modifiedCount} modified, ${bulkWriteResult.deletedCount} deleted.` |
| 142 | ); |
| 143 | if (bulkWriteResult.hasWriteErrors()) { |
| 144 | console.warn(`Write errors encountered:`); |
| 145 | bulkWriteResult |
| 146 | .getWriteErrors() |
| 147 | .forEach((err) => console.warn(` - Index ${err.index}: ${err.errmsg}`)); |
| 148 | } |
| 149 | } catch (err) { |
| 150 | console.error(`Error executing bulk write for collection '${collectionName}':`, err); |
| 151 | } |
| 152 | } |
| 153 | |
| 154 | /** |
| 155 | * Helper function to update the corresponding index collection. |
no outgoing calls
no test coverage detected