Get Key for object created after Push (Angular and Firebase)

a 夏天 提交于 2019-12-04 04:58:14

问题


I'm having problems understanding how to use Firebase. I wrote a function to push some data in my firebase database. I need to get the Key generated after I push the data into my db.

This is my function

  postData(order: orderInfo) {
    let uid = firebase.auth().currentUser.uid;
    this.db.list('transactions').push({
      currency: order.currency,
      total: order.total,
      rate: order.rate,
      uid: uid
    });
    console.log(order.$key);
    this.db.list('transactionsPerUser').update(uid, order.$key);
  }

When I push the data to transactions path, it also pushes user uid so I can link the data from my user database to transactions database. What I want now is to link in other part of my database the transactions made by users, something like this:

transactionsPerUser {
     user1 {
           order.$key (key generated by push) : "true"
                     }
            {

As you can see, I'm trying to console.log(order.$key) but it returns undefined. How can I solve this?? and second, is this a proper way to structure my database? Thanks for your help!


回答1:


I would make a small change to the post line and add / to the transactions

postData(order: orderInfo) {
    let uid = firebase.auth().currentUser.uid;

// Change this next line to save the transaction

    var newRef = this.db.list('/transactions').push({
      currency: order.currency,
      total: order.total,
      rate: order.rate,
      uid: uid
    });

// get just the key reference
var newKey= newRef.key;

//then change this refer

    console.log(newKey);

//To update you would change the next line

    this.db.list('transactionsPerUser').update(newKey, order.newInfo);
}


来源:https://stackoverflow.com/questions/45340219/get-key-for-object-created-after-push-angular-and-firebase

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!