So I am trying to use batched writes in my firebase function to batch my writes in batches of 500. However for some reason I am getting the error "Error: Cannot modify a WriteBatch that has been committed." and can't seem to spot what I am doing wrong. It is storing the first few results but after that it is giving me the error in my cloud functions log. Any suggestions would be appreciated =D
messages.forEach((item, index) => {
var all = _.find(item.parts, { which: "" });
var id = item.attributes.uid;
var idHeader = "Imap-Id: " + id + "\r\n";
// eslint-disable-next-line handle-callback-err
simpleParser(idHeader + all.body, (err, mail) => {
// access to the whole mail object
console.log(mail.subject);
console.log(mail.html);
let newDate = mail.date.valueOf();
batch.set(
docRef,
{
Emails: admin.firestore.FieldValue.arrayUnion(
JSON.stringify({
subject: mail.subject,
body: mail.text,
date: newDate,
from: mail.from,
})
),
//....
},
{ merge: true }
);
if (
(index % 500 === 0 && index > 0) ||
index === messages.length - 1
) {
return batch.commit().then(() => {
return console.log("SUCCESS");
});
}
});
});