How to copy or move firebase object from one path to another

I will here explain how you can copy or move firebase object from path to another path. You can call the firebase object a firebase record too. Steps to copy or move firebase object are below-

Move function

function moveFirebaseObject(oldRef, newRef) {
    oldRef.take(1).subscribe(snapshot => {
        newRef.set(snapshot);      // this line is used to Set the object at new path
        oldRef.remove();           // this line removes the old object from the old path
    })
}

Above function explanation

I have created a moveFirebaseObject() function which accepts two parameters at the time of call:- oldRef and newRef

oldRef is the reference of the Old Firebase Object from where you want to move the object to new location.

newRef is the reference of the New Firebase Object where you want to move the object.

The function listens the data for only once and sets the object at new location. As well as it removes the old object from old location.

Call the moveFirebaseObject function

var oldRef = this.db.object(`/item-at-old-path`);              // pass the complete path of the firebase object from root
var newRef = this.db.object(`/item-should-be-at-new-path`);    // pass the complete path of the new path where you want the object to move
moveFirebaseObject(oldRef, newRef);

 

Copy function

function copyFirebaseObject(oldRef, newRef) {
    oldRef.take(1).subscribe(snapshot => {
        newRef.set(snapshot);      // this line is used to Set the object at new path
    })
}

Copy function is almost similar to Move function. The only difference is that, you don’t need to remove the firebase object from its old path.

oldRef is the reference of the Old Firebase Object from where you want to move the object to new location.

newRef is the reference of the New Firebase Object where you want to move the object.

The function listens the data for only once and sets the object at new location. It doesn’t remove the object from old path.

Call the copyFirebaseObject function

var oldRef = this.db.object(`/item-at-old-path`);              // pass the complete path of the firebase object from root
var newRef = this.db.object(`/item-should-be-at-new-path`);    // pass the complete path of the new path where you want the object to move
copyFirebaseObject(oldRef, newRef);

Hope I was able to explain the functions well.

Would love to hear your comments below 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *