Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularFire2 how to use your own custom key instead of the auto generated one

Currently I am using:

this.af.database.list('users').push(user);

How can I make the key of the object that is submitted be custom. So I want to be able to set the node of this object to the same uid of the registered user. I have access to this Id I just need to be able to know how to make the custom user objects node not be the auto generated id when pushing.

Thanks

like image 761
Jason Avatar asked Nov 10 '16 09:11

Jason


4 Answers

Use a method like below with Angularfire2

addCustomKey (key, value) {
    const toSend = this.af.database.object(`/users/${key}`);
    toSend.set(value);
}
like image 100
Jesse Te Weehi Avatar answered Oct 21 '22 09:10

Jesse Te Weehi


Here is another method you can use with AngularFire2

addCustomKey(key, value) {
    const users = this.af.database.object('/users');
    users.update({ [key]: value });
}
like image 26
Tolga Avatar answered Oct 21 '22 10:10

Tolga


push will add a push key, just use the update method:

this.yourRef = this.af.database.list('users');
let userId = "UID", 
userInfos = { data: "your user datas" };

this.yourRef.update(userId, userInfos);
like image 23
t3__rry Avatar answered Oct 21 '22 10:10

t3__rry


As mentioned in many of the answers above, calling push() will generate a key for you. Here's an alternative approach.

Instead, you have to use child() if you want set your custom key to determine the key/path for yourself. Like so:

firebase.database.ref().child('/path/with/custom/key/goes/here').set();

In your case, to use the user's authentication ID, here's how you approach it:

export class SomeClass {

    uid: string;

    constructor(public afDB: AngularFireDatabase, public afAuth: AngularFireAuth) {

          // Get User Auth ID
          afAuth.authState.subscribe(user => {
            this.uid = user.uid;
          });
      }

    //Your method
    this.afDB.database.ref().child(`users/${this.uid}/`).set(user);
}
like image 41
mondieki Avatar answered Oct 21 '22 08:10

mondieki