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

8

8

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

Dearborn answered 10/11, 2016 at 9:53 Comment(0)
P
10

Use a method like below with Angularfire2

addCustomKey (key, value) {
    const toSend = this.af.database.object(`/users/${key}`);
    toSend.set(value);
}
Providential answered 20/12, 2016 at 5:43 Comment(2)
As of my comment date this approach errors out due to the /${key}. I replaced it with a variable but that ads my custom key as a value to the node.Amadis
is this firestore or RealTime DB?Heading
A
5

Here is another method you can use with AngularFire2

addCustomKey(key, value) {
    const users = this.af.database.object('/users');
    users.update({ [key]: value });
}
Auspex answered 12/1, 2017 at 3:39 Comment(0)
P
2

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);
Pattern answered 24/3, 2017 at 13:30 Comment(1)
Not sure how you can update something that doesn't have a key yet. As of this date this fails with error: First argument must be an object containing the children to replace.Amadis
I
2

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);
}
Indoctrinate answered 1/4, 2018 at 17:40 Comment(0)
C
1

vanilla js looks something like this:

//to generate a key do something like
var id = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
  var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
  return v.toString(16);
});

function setNode(key){
  if (key){
    var thisRef = ref.child('testLocation');
    var obj = {};
    obj[key] = true;
    thisRef.update(obj, onComplete);
  }
}
Centiliter answered 12/1, 2017 at 3:50 Comment(0)
A
1

Pass in your custom key, in this case projectKey which is a variable you populate from somewhere:

private whatEverName(projectKey) {
    this.projectKey = projectKey;
    this.af.object('/Projects/' + this.projectKey);
}

Call whatEverName(projectKey) in your code somewhere and you have a custom node key. This advice is current as of 25 July, 2017.

I've added a bit more here to help those who are trying to create a child node to the one above with another push key as a custom key. This is useful for an association index under that project, such as a list of users working on that project. You may not want this list in the project data but get it by query. This makes it easier to denormalize the data and have a flatter architecture, the Firebase goal.

That association node is called ProjectsMembers in this case and we are recording the project's owner in it. Add other user nodes the same way. Notice the backticks!!! Single quotes won't work. In this case I set an owner name as a reference to push key. Easier to read in the db.

// Add child node with project key as push key to the association index.
this.af.object(`ProjectsMembers/${projectKey}/` + this.ownerKey)
   .set({ ownerName: this.ownerName });
Amadis answered 25/7, 2017 at 16:27 Comment(0)
L
0

Just do it with a regular firebase method like this:

var updates = {};
  updates['/users/' + userId] = newUserData;

return firebase.database().ref().update(updates);

Anything in your scope that is bound to your list will reflect the update.

Read and Write Data on the Web

Lundberg answered 10/11, 2016 at 13:11 Comment(3)
.ref seems to be outdated by July 2017.Amadis
Can you be more specific?Lundberg
ksav - I've been reading that .ref is deprecated but don't have sources. Check the docs and search online.Amadis
O
0

This is the simplest approach I'm suggesting.

import { Component, OnInit } from '@angular/core';
import { AngularFireDatabase } from '@angular/fire/database';

@Component({
  selector: 'app-mycomponent',
  templateUrl: './mycomponent.page.html',
  styleUrls: ['./mycomponent.page.scss'],
})
export class MyComponent implements OnInit {

  constructor(
    private db: AngularFireDatabase
  ) { }

  ngOnInit() {}

  submit(user) {
    this.db.database.ref('users').child('your_custom_key').set(user)
  }
}

Orland answered 25/10, 2021 at 11:21 Comment(1)
Can you explain what you changed and how it works ?Indenture

© 2022 - 2024 — McMap. All rights reserved.