Skip to content

Instantly share code, notes, and snippets.

@vlilloh
Created November 5, 2018 06:47
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save vlilloh/25ef70ae3c9f57a5ba6f1af621cd7019 to your computer and use it in GitHub Desktop.
Save vlilloh/25ef70ae3c9f57a5ba6f1af621cd7019 to your computer and use it in GitHub Desktop.
[Firebase] Move a collection in Cloud Firestore with a Cloud Function
exports.mv = functions.https.onRequest(request => {
const mv = async (collRefSource, collRefDest) => {
const querySnapshot = await collRefSource.get();
querySnapshot.forEach(async docSnapshot => {
(async () => {
await collRefDest.doc(docSnapshot.id).set(docSnapshot.data());
docSnapshot.ref.delete();
})();
const collRefs = await docSnapshot.ref.getCollections();
for (const collRef of collRefs)
mv(collRef, collRefDest.doc(docSnapshot.id).collection(collRef.id))
});
};
const collRefSource = admin.firestore().collection(request.query.collPathSource);
const collRefDest = admin.firestore().collection(request.query.collPathDest);
mv(collRefSource, collRefDest);
});
// Example: https://us-central1-{project-id}.cloudfunctions.net/mv?collPathSource=collection1%2Fdocument1%2Fcollection2&collPathDest=collection3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment