I have a user object in firebase that I need to move to another child node on the same tree.
The structure is like so:
users -> male -> uid -> ......KVPs..objects...etc
-> female -> uid -> ......KVPs..objects...etc
I need to keep users separated by gender due to the nature of the app.
If a user changes their gender I want to move all their details to that selected gender.
I tried using AngularFire (firebaseObject) but it throws errors when I tried to set it in firebase due to the keys present in the object. I tried striping out the keys, using JSON.stringify, angular.toJSON but am not having any luck!!
I'm wondering is there a cleaner or recommended way to do this?
Appreciate If anyone has any pointers or can assist in anyway.
Many Thanks,
Noel
This is actually pretty easy
// firebase ref
desc.ref1 = new Firebase(desc.userRef+'/'+desc.oldGender+'/'+uid);
desc.ref2 = new Firebase(desc.userRef+'/'+desc.gender+'/'+uid);
desc.ref1.on("value", function(snapshot) {
console.log(snapshot.val());
desc.ref2.set(snapshot.val());
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
I would actually suggest changing the structure instead of moving nodes around
users
uid_0
name: "some name"
gender: "male"
loc: "US"
uid_1
name: "another name"
gender: "female"
loc: "FR"
It still provides separation of gender but far more flexibility to change name, gender, location or whatever without having to read, remove, and rewrite existing data.
It also is far more flexible for queries and adding additional data to each user.
I may not work for this use case but in big-picture it's best practice.
Thanks for responding. I had it like this originally and I still capture the gender under the UID but I wanted to separate males and females. My app is for dating so I'm thinking it will be more efficient for doing searches based on the preferred sex attribute. I would think ~50% less nodes to search through initially. If you have some advice on this, would love to hear as I'm not too up on performance best practices for firebase/JSON.
I'm going to post the code I used for copying and cleaning up as might be helpful to someone. I had problems with 'on' listener, it was deleting both nodes. Changing this to 'once' resolved it.
// firebase refs
desc.ref1 = new Firebase(desc.userRef+'/'+desc.oldGender+'/'+uid);
desc.ref2 = new Firebase(desc.userRef+'/'+desc.gender+'/'+uid);
// copy user object
desc.ref1.once("value", function(snapshot) {
// copy user data to new gender tree
desc.ref2.set(snapshot.val(), function(error) {
if (error) {
$log.info("could not copy user object." + error);
} else {
$log.info("user object copied successfully.");
// remove user object under old gender
desc.ref1.remove(desc.onComplete);
}
});
}, function (errorObject) {
$log.info("The read failed: " + errorObject.code);
});