I want to create record in other doctype but there is an error

Hi, can somebody help me with this, i made a custom field in Purchase Order called “Equipment”, i want to create a subsidiary ledger in the Equipment doctype for every transactions in Purchase Order including the item code and other info like po no, date. My script loops in the child table Purchase Invoice Item and create new record in the doctype “Equipment Ledger Items” which is the child table of doctype “Equipment” using the frappe.db.insert, here is my code:

frappe.ui.form.on(‘Purchase Order’, {
onload: function(frm) {
frm.add_custom_button(__(‘Ledger’), function() {
if (frm.doc.workflow_state === “Approved”) {
const itemCodes = []; // Declare an array to store item codes

			frappe.model.with_doc('Equipment', frm.doc.for_equipment, function() {
				var equipment_master = frappe.get_doc('Equipment', frm.doc.for_equipment);

				if (equipment_master && equipment_master.enable_ledger) {
					for (let i = 0; i < frm.doc.items.length; i++) {
						const child = frm.doc.items[i];
						var itemCode = child.item_code;
						itemCodes.push(itemCode); // Push each itemCode into the array
					}

					// Loop through the itemCodes array and display each item code
					for (let j = 0; j < itemCodes.length; j++) {
						frappe.msgprint('Item Code ' + (j + 1) + ': ' + itemCodes[j]);
						var new_equipment_ledger_entry = {
							'doctype': 'Equipment Ledger Items',
							'parenttype': 'Equipment',
							'parent': equipment_master.name,
							'parentfield': 'ledger_items',
							'item_code': itemCodes[j],
						
						};

						// Create a new record in the child table using frappe.db.insert
						frappe.db.insert(new_equipment_ledger_entry);
						frm.reload_doc();
					}

					// Refresh the form after all updates are done
				
				} else {
					frappe.msgprint('Equipment ledger is not enabled or equipment not found.');
				}
			});
		} else {
			frappe.msgprint('Purchase Order must be in "Approved" state to update the ledger.');
		}
	});
}

});

but the problem is it is giving an error when processing the last record, this is the error i get:

Error: Document has been modified after you have opened it (2023-09-05 15:12:54.068136, 2023-09-05 15:12:54.072775). Please refresh to get the latest document.
Error updating child records: undefined:

What could be the problem with the code? Please help me. Thank you in advance.