简体   繁体   中英

How to save the objects uid when I push the data in firebase database list, using javascript

I want to save the uid when I push new data in Firebase database. This is possible not for auth users but for data objects.

For example, I want this object schema:

"-Kdsfdsg555555fdsgfsdgfs" : {  <------- I want this id
  Id : "Kdsfdsg555555fdsgfsdgfs",   <--- How to put that inside 
  name : "A",
  time_updated : "6/6/2017"
}

Is any way how to get this id and pushed inside the object?

My code is as follows:

categories: FirebaseListObservable<any[]>; 

this.categories = this.db.list('/categories') as FirebaseListObservable<Category[]>;

addCategory(category: any) {
    return this.categories.push(category).then( snap => {
      this.openSnackBar('New category has been added', 'ok');

    }).catch(error => {
      this.openSnackBar(error.message, 'ok');
    });
  }

There are two ways to use Firebase's push() method:

  • By passing in an argument, it will generate a new location and store the argument there.
  • By passing in no arguments, it will just generate a new location.

You can use the second way of using push() to just get the new location or its key:

addCategory(category: any) {
  var newRef = this.categories.push();
  category.Id = newRef.key;
  newRef.set(category).then( snap => {
    this.openSnackBar('New category has been added', 'ok');
  }).catch(error => {
    this.openSnackBar(error.message, 'ok');
  });
}

But note that it's typically an anti-pattern to store the key of an item inside that item itself too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM