Mar 22, 2023 09:28 AM
Hello, folks, i am trying to change the filename for files in an attachment field, and i noticed that when there are a few records it seems like the names get changed, but when i try to process more than 30, the attachments automatically get removed. I also noticed that the comments in the records id indicate that two actions have taken place
But for the ones that worked it shows just one time the record has been edited
The script that i use is below, i noticed a similar behavior when i was trying to upload attachments from a URL as well, some get updated, while some do not.
// Define the table, view, and field names
const tableName = 'StuTable';
const viewName = 'StuMissingcert';
const attachmentFieldName = 'medicalupload';
const studentIDFieldName = 'id';
// Select the table, view, and get the records
const table = base.getTable(tableName);
const view = table.getView(viewName);
const records = await view.selectRecordsAsync();
// Iterate through the records
for (let record of records.records) {
// Get the attachment field data and student ID
const attachments = record.getCellValue(attachmentFieldName);
const studentID = record.getCellValue(studentIDFieldName);
// Check if there are attachments
if (attachments && attachments.length > 0) {
// Replace the file names with the student ID
const updatedAttachments = attachments.map(attachment => {
// Use the student ID as the new file name
const newFileName = studentID;
return {
url: attachment.url,
filename: newFileName
};
});
// Update the record with the new file names
await table.updateRecordAsync(record, {
[attachmentFieldName]: updatedAttachments
});
}
}
Mar 23, 2023 07:00 AM
Hi,
I'm not sure if this a reason, but using single update actions in a loop can cause problems. Airtable has limit for updates per second (15 or 25, I can't remember). If your computer is slow enough or operation inside loop exceed some amount of milliseconds to execute, then script will run OK. But that's a matter of luck, the correct way is to form array of updates and then use updateRecordsAsync.
Mar 23, 2023 07:23 AM
I also noticed that you use the same filename for all attachments in record (according to value of 'id' field), but it cannot be the reason.
anyway, I refactored your script (under 7th line) and it worked, you can try
const records = await view.selectRecordsAsync();
const value = record => record.getCellValue(attachmentFieldName);
const newID = record => record.getCellValue(studentIDFieldName);
const filtered=records.records.filter(r=>value(r)&&value(r).length)
const newnames=r=>value(r).map(a=>({'url':a.url,'filename':newID(r)}))
const update=r=>({id:r.id,fields:{[attachmentFieldName]:newnames(r)}})
const upd=filtered.map(update)
while (upd.length) await table.updateRecordsAsync(upd.splice(0,50))