I am sharing how I have been working with firestore bulk operations. In my app I use this basic code:
- The action is the kind of operation you want to preform: insert a new document, update fields in a document, overwrite and set new fields in the document, and delete the document.
- Provide the reference ID or leave null if inserting a new document.
Populate the batchArray with as many iterations of updates, inserts, etc you want.
const batchArray = [];
batchArray.push({//send to batch for inserting into FireStore
action:"insert", //options: insert, update, set, delete
collection:'Students',
id:null, //id or null
data: {name : "Jeff"}
})
//console.log(batchArray);
firestoreBatch.trigger({additionalScope: { batchObj: batchArray }})
2 Likes
This is the next code "firestoreBatch" which I have in my query library.
The "replaceKeyValue" function is to replace any "timestamp" in my data with a date object. If adding in a date prior to this code the date becomes a string. By putting it at this stage it sends it as an object.
Then the code builds out the reference path with the "collection" and "id" if provided. Checks the action and lastly commits the whole thing.
function replaceKeyValue(obj, keyToFind, newValue) {
// Iterate through each key in the object
for (const key in obj) {
// If the key matches the one we're looking for, replace its value
if (key === keyToFind) {
obj[key] = newValue;
}
// If the value is an object or array, call the function recursively
else if (typeof obj[key] === 'object' && obj[key] !== null) {
replaceKeyValue(obj[key], keyToFind, newValue);
}
}
}
const batch = db.firestore().batch();
for (const obj of batchObj){
replaceKeyValue(obj, 'timestamp', moment()); //insert moment() so that firestore gets a date objects
let id = obj.id ? db.firestore().collection(obj.collection).doc(obj.id) : db.firestore().collection(obj.collection).doc();
switch (obj.action) {
case "insert":
batch.set(id, {...obj.data, "timestamp": moment()});
break;
case "update":
batch.update(id, {...obj.data, "timestamp": moment()});
break;
case "set":
batch.set(id, {...obj.data, "timestamp": moment()});
break;
case "delete":
batch.delete(id);
break;
default:
// handle other cases if needed
break;
}
}
return await batch.commit();
Update.
To get the raw code mode in QueryLibrary you first have to create a raw mode in an app and then export it to the library. QueryLibrary has no option otherwise.