I’m currently working on a project that involves moving data from one Firestore collection to another using JavaScript and the Firebase SDK. I’ve encountered an issue when trying to use the doc function inside a forEach loop.
Here’s a simplified version of the code I’m using:
// Import necessary Firebase libraries and initialize Firebase app
async function moveData() {
const db = getFirestore(app);
const sourceCollectionRef = collection(db, 'sourceCollection');
const targetCollectionRef = collection(db, 'targetCollection');
const querySnapshot = await getDocs(sourceCollectionRef);
querySnapshot.forEach(async (doc) => {
const docId = doc.id;
const targetDocRef = doc(targetCollectionRef, docId); // This line doesn't work
// Some logic to manipulate data
// Attempt to set data to targetDocRef
await setDoc(targetDocRef, /* modified data */);
});
}
The issue I’m facing is that the doc function doesn’t seem to work inside the forEach loop. I’m receiving an error saying that doc is not a function.
I’ve tried various approaches, including defining targetDocRef outside of the loop and passing docId as a parameter to it, but I still face the same issue.
What I Tried:
- Inside the forEach loop, I attempted to use the doc function to create a reference to a document in Firestore’s target collection.
- I passed the targetCollectionRef and the docId as arguments to the doc function, expecting it to return a reference to the target document.
- I then attempted to use setDoc to set data to the target document.
I was expecting that this code would create a reference to the target document for each document in the source collection and allow me to set data to the target documents.
However, I encountered an issue where the doc function inside the forEach loop was not recognized, and I received an error saying that doc is not a function.
I’m looking for an alternative solution or insights on how to correctly reference documents inside a loop in Firestore using JavaScript and the Firebase SDK.